From 5618c4c1f7f427d7672f3756c681860c1837dc91 Mon Sep 17 00:00:00 2001 From: Johan x Lindqvist Date: Wed, 18 Sep 2019 13:48:29 +0200 Subject: [PATCH] Always access the exception property on the task if it has status IsFaulted. By checking the Exception property it will consider the task exception as handled which means the finalizer won't throw an unhandled task exception. --- Source/MQTTnet/Client/MqttClient.cs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) 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);