Fix cancellation issues when connecting.

This commit is contained in:
Christian
2021-01-01 15:56:38 +01:00
parent 74e952bb03
commit 75845d6416
4 changed files with 17 additions and 5 deletions
@@ -13,8 +13,8 @@ namespace MQTTnet.Exceptions
{
}
public MqttCommunicationException(string message)
: base(message)
public MqttCommunicationException(string message, Exception innerException = null)
: base(message, innerException)
{
}
}
@@ -4,6 +4,7 @@ using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet.Exceptions;
namespace MQTTnet.Implementations
{
@@ -123,9 +124,19 @@ namespace MQTTnet.Implementations
_networkStream = new NetworkStream(_socket, true);
}
}
catch (SocketException socketException)
{
if (socketException.SocketErrorCode == SocketError.OperationAborted)
{
throw new OperationCanceledException();
}
throw new MqttCommunicationException($"Error while connecting with host '{host}:{port}'.", socketException);
}
catch (ObjectDisposedException)
{
// This will happen when _socket.EndConnect gets called by Task library but the socket is already disposed.
cancellationToken.ThrowIfCancellationRequested();
}
}