spread dispose pattern

This commit is contained in:
JanEggers
2019-12-21 09:09:03 +01:00
parent 698f0b66d2
commit a77e0b8dde
5 changed files with 64 additions and 53 deletions
@@ -10,10 +10,11 @@ using System.Runtime.ExceptionServices;
using System.Threading;
using MQTTnet.Channel;
using MQTTnet.Client.Options;
using MQTTnet.Internal;
namespace MQTTnet.Implementations
{
public class MqttTcpChannel : IMqttChannel
public class MqttTcpChannel : Disposable, IMqttChannel
{
private readonly IMqttClientOptions _clientOptions;
private readonly MqttClientTcpOptions _options;
@@ -94,7 +95,7 @@ namespace MQTTnet.Implementations
public Task DisconnectAsync(CancellationToken cancellationToken)
{
Dispose();
Cleanup();
return Task.FromResult(0);
}
@@ -158,7 +159,7 @@ namespace MQTTnet.Implementations
}
}
public void Dispose()
private void Cleanup()
{
// When the stream is disposed it will also close the socket and this will also dispose it.
// So there is no need to dispose the socket again.
@@ -177,6 +178,15 @@ namespace MQTTnet.Implementations
_stream = null;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Cleanup();
}
base.Dispose(disposing);
}
private bool InternalUserCertificateValidationCallback(object sender, X509Certificate x509Certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (_options.TlsOptions.CertificateValidationCallback != null)
@@ -112,7 +112,7 @@ namespace MQTTnet.Implementations
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, cancellationToken).ConfigureAwait(false);
}
Dispose();
Cleanup();
}
public async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
@@ -146,24 +146,29 @@ namespace MQTTnet.Implementations
{
if (disposing)
{
_sendLock?.Dispose();
_sendLock = null;
try
{
_webSocket?.Dispose();
}
catch (ObjectDisposedException)
{
}
finally
{
_webSocket = null;
}
Cleanup();
}
base.Dispose(disposing);
}
private void Cleanup()
{
_sendLock?.Dispose();
_sendLock = null;
try
{
_webSocket?.Dispose();
}
catch (ObjectDisposedException)
{
}
finally
{
_webSocket = null;
}
}
private IWebProxy CreateProxy()
{
if (string.IsNullOrEmpty(_options.ProxyOptions?.Address))