我有一个类可以通过TCP/IP对外部设备建模。这个类创建一个客户机,它基本上是System.Net.Sockets.TcpClient的包装器,该类的实例由应用程序类持有。
根据https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose#cascade-dispose-calls,如果一个类拥有一个实现IDisposable的字段,那么它也应该实现IDisposable。
因此,在我的情况下,TcpClient实现了IDisposable,因此我的客户机类必须实现IDisposable,因此我的外部设备类必须实现IDisposable,因此我的应用程序类必须实现IDisposable。
听起来很麻烦,所以我怀疑这是否是正确的方法?
public class Client : IDisposable
{
private TcpClient _tcpClient;
...
public void Connect()
{
_tcpClient = new TcpClient();
if (!_tcpClient.ConnectAsync(address, port).Wait(1000))
...
}
public void Disconnect()
{
_tcpClient?.Dispose();
_tcpClient = null;
}
#region IDisposable
...
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
_tcpClient?.Dispose();
_tcpClient = null;
}
_disposed = true;
}
#endregion
...
}
public class SM15k : IDisposable
{
private readonly Client _client;
...
public SM15k()
{
_client = new Client();
}
#region IDisposable
...
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
_client.Dispose();
}
_disposed = true;
}
#endregion
...
}
public class App : IDisposable
{
private SM15k _SM15k;
#region IDisposable
...
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
_SM15k?.Dispose();
_SM15k = null;
}
_disposed = true;
}
#endregion
...
}发布于 2020-07-17 08:04:11
是的,这是正确的方法。
因为您有需要处理的依赖项,所以您必须确保它们一直被释放。否则,当您释放“外部设备类”时,底部的TcpClient将不会被正确地处理,您可能会遇到资源泄漏(例如,端口仍然打开)。
https://stackoverflow.com/questions/62949557
复制相似问题