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.
This commit is contained in:
Johan x Lindqvist
2019-09-18 13:49:59 +02:00
parent ba9ceed7ce
commit 5618c4c1f7
+18 -3
View File
@@ -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);