From c3c0dcf31334da01518f02e3b5c422a8c40a01e5 Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Thu, 6 Jun 2019 19:32:00 +0200 Subject: [PATCH] Execute disconnected handler in new task. --- Source/MQTTnet/Client/MqttClient.cs | 7 +++++-- Source/MQTTnet/Internal/TaskExtensions.cs | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 Source/MQTTnet/Internal/TaskExtensions.cs diff --git a/Source/MQTTnet/Client/MqttClient.cs b/Source/MQTTnet/Client/MqttClient.cs index 76bceee..f84d277 100644 --- a/Source/MQTTnet/Client/MqttClient.cs +++ b/Source/MQTTnet/Client/MqttClient.cs @@ -13,6 +13,7 @@ using MQTTnet.Client.Subscribing; using MQTTnet.Client.Unsubscribing; using MQTTnet.Diagnostics; using MQTTnet.Exceptions; +using MQTTnet.Internal; using MQTTnet.PacketDispatcher; using MQTTnet.Packets; using MQTTnet.Protocol; @@ -287,7 +288,9 @@ namespace MQTTnet.Client var disconnectedHandler = DisconnectedHandler; if (disconnectedHandler != null) { - await disconnectedHandler.HandleDisconnectedAsync(new MqttClientDisconnectedEventArgs(clientWasConnected, exception, authenticateResult)).ConfigureAwait(false); + // This handler must be executed in a new thread because otherwise a dead lock may happen + // when trying to reconnect in that handler etc. + Task.Run(() => disconnectedHandler.HandleDisconnectedAsync(new MqttClientDisconnectedEventArgs(clientWasConnected, exception, authenticateResult))).Forget(_logger); } } } @@ -648,4 +651,4 @@ namespace MQTTnet.Client return Interlocked.CompareExchange(ref _disconnectGate, 1, 0) != 0; } } -} +} \ No newline at end of file diff --git a/Source/MQTTnet/Internal/TaskExtensions.cs b/Source/MQTTnet/Internal/TaskExtensions.cs new file mode 100644 index 0000000..733631c --- /dev/null +++ b/Source/MQTTnet/Internal/TaskExtensions.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; +using MQTTnet.Diagnostics; + +namespace MQTTnet.Internal +{ + public static class TaskExtensions + { + public static void Forget(this Task task, IMqttNetChildLogger logger) + { + task?.ContinueWith(t => + { + logger.Error(t.Exception, "Unhandled exception."); + }, + TaskContinuationOptions.OnlyOnFaulted); + } + } +}