Fix Xamarin connect freeze (#1545)

This commit is contained in:
Christian
2022-10-23 07:51:19 +02:00
committed by GitHub
parent 7823d8342e
commit 36736914bc
3 changed files with 23 additions and 3 deletions
@@ -123,7 +123,7 @@ namespace MQTTnet.Tests.Client
//Assert.IsInstanceOfType(exception.InnerException, typeof(SocketException));
}
await Task.Delay(100); // disconnected handler is called async
await LongTestDelay(); // disconnected handler is called async
Assert.IsTrue(disconnectHandlerCalled);
}
}
+21 -2
View File
@@ -23,7 +23,7 @@ namespace MQTTnet.Adapter
{
const uint ErrorOperationAborted = 0x800703E3;
const int ReadBufferSize = 4096;
readonly IMqttChannel _channel;
readonly byte[] _fixedHeaderBuffer = new byte[2];
readonly MqttNetSourceLogger _logger;
@@ -73,7 +73,26 @@ namespace MQTTnet.Adapter
try
{
await _channel.ConnectAsync(cancellationToken).ConfigureAwait(false);
/*
* We have to implement a small workaround here to support connecting in Xamarin
* with a disabled WiFi network. If the WiFi is disabled the connect method will
* block forever. Even a cancellation token is not supported properly.
*/
var connectTask = _channel.ConnectAsync(cancellationToken);
var timeout = new TaskCompletionSource<object>();
using (cancellationToken.Register(() => timeout.TrySetResult(null)))
{
await Task.WhenAny(connectTask, timeout.Task).ConfigureAwait(false);
if (timeout.Task.IsCompleted && !connectTask.IsCompleted)
{
throw new OperationCanceledException("MQTT connect cancelled.", cancellationToken);
}
// Make sure that the exception from the connect task gets thrown.
await connectTask.ConfigureAwait(false);
}
}
catch (Exception exception)
{