diff --git a/Source/MQTTnet/Client/MqttClient.cs b/Source/MQTTnet/Client/MqttClient.cs index c5224cb7..6717f610 100644 --- a/Source/MQTTnet/Client/MqttClient.cs +++ b/Source/MQTTnet/Client/MqttClient.cs @@ -271,7 +271,7 @@ namespace MQTTnet.Client var receiverTask = WaitForTaskAsync(_packetReceiverTask, sender); var keepAliveTask = WaitForTaskAsync(_keepAlivePacketsSenderTask, sender); - + await Task.WhenAll(receiverTask, keepAliveTask).ConfigureAwait(false); _logger.Verbose("Disconnected from adapter."); @@ -628,13 +628,28 @@ namespace MQTTnet.Client return true; } - private static async Task WaitForTaskAsync(Task task, Task sender) + private async Task WaitForTaskAsync(Task task, Task sender) { - if (task == sender || task == null) + if (task == null) { return; } + if (task == sender) + { + // Return here to avoid deadlocks, but first any eventual exception in the task + // must be handled to avoid not getting an unhandled task exception + if (!task.IsFaulted) + { + return; + } + + // By accessing the Exception property the exception is considered handled and will + // not result in an unhandled task exception later by the finalizer + _logger.Warning(task.Exception, "Exception when waiting for background task."); + return; + } + try { await task.ConfigureAwait(false);