From 699558e47a86d09511c1dee2c3fc53750e21ce24 Mon Sep 17 00:00:00 2001 From: Jimmy Rosenskog Date: Thu, 3 Oct 2019 09:46:40 +0200 Subject: [PATCH] Added exception handling to make sure all tasks are observed to avoid UnobservedTaskException. --- Source/MQTTnet/Client/MqttClient.cs | 37 ++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/Source/MQTTnet/Client/MqttClient.cs b/Source/MQTTnet/Client/MqttClient.cs index 8520374..527a5cd 100644 --- a/Source/MQTTnet/Client/MqttClient.cs +++ b/Source/MQTTnet/Client/MqttClient.cs @@ -258,28 +258,34 @@ namespace MQTTnet.Client var clientWasConnected = IsConnected; TryInitiateDisconnect(); + IsConnected = false; try { - IsConnected = false; - if (_adapter != null) { _logger.Verbose("Disconnecting [Timeout={0}]", Options.CommunicationTimeout); await _adapter.DisconnectAsync(Options.CommunicationTimeout, CancellationToken.None).ConfigureAwait(false); } - var receiverTask = WaitForTaskAsync(_packetReceiverTask, sender); - var keepAliveTask = WaitForTaskAsync(_keepAlivePacketsSenderTask, sender); - - await Task.WhenAll(receiverTask, keepAliveTask).ConfigureAwait(false); - _logger.Verbose("Disconnected from adapter."); } catch (Exception adapterException) { _logger.Warning(adapterException, "Error while disconnecting from adapter."); } + + try + { + var receiverTask = WaitForTaskAsync(_packetReceiverTask, sender); + var keepAliveTask = WaitForTaskAsync(_keepAlivePacketsSenderTask, sender); + + await Task.WhenAll(receiverTask, keepAliveTask).ConfigureAwait(false); + } + catch (Exception e) + { + _logger.Warning(e, "Error while waiting for tasks."); + } finally { Dispose(); @@ -346,11 +352,24 @@ namespace MQTTnet.Client try { await _adapter.SendPacketAsync(requestPacket, Options.CommunicationTimeout, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + _logger.Warning(e, "Error when sending packet of type '{0}'.", typeof(TResponsePacket).Name); + packetAwaiter.Cancel(); + } + + try + { return await packetAwaiter.WaitOneAsync(Options.CommunicationTimeout).ConfigureAwait(false); } - catch (MqttCommunicationTimedOutException) + catch (Exception exception) { - _logger.Warning(null, "Timeout while waiting for packet of type '{0}'.", typeof(TResponsePacket).Name); + if (exception is MqttCommunicationTimedOutException) + { + _logger.Warning(null, "Timeout while waiting for packet of type '{0}'.", typeof(TResponsePacket).Name); + } + throw; } }