需要在使用TcpClient的类上实现终结器吗?

5 c# idisposable finalizer unmanagedresources

我有一个类(比如说MyClass)使用(作为私有字段)一个TcpClient对象.MyClass实现IDisposable调用TcpClient.CloseDispose方法.

我的问题是MyClass还应该实现一个终结器来调用Dispose(bool Disposing)释放TcpClient’s非托管资源,以防MyClass.Dispose调用代码没有调用?

谢谢

thi*_*ing 4

不,你不应该。

因为您不应该在终结器中调用其他对象的方法,所以它可能在您的对象之前被终结。

TcpClient 的终结器将由垃圾收集器调用,所以让他来做吧。

Dispose 中的模式是:

protected virtual void Dispose(bool disposing)
{
   if (disposing)
   { 
      // dispose managed resources (here your TcpClient)
   }

   // dispose your unmanaged resources 
   // handles etc using static interop methods.
}
Run Code Online (Sandbox Code Playgroud)