Search code examples
c#idisposablefinalizerunmanagedresources

Need to implement a finalizer on a class that uses TcpClient?


I have a class (say MyClass) that uses (has as a private field) a TcpClient object. MyClass implements IDisposable calling TcpClient.Close in the Dispose method.

My question is should MyClass also implement a finalizer to call Dispose(bool Disposing) to free the TcpClient’s unmanaged resources in case MyClass.Dispose is not called by the calling code?

Thanks


Solution

  • No you shouldn't.

    Because you should never call a method on an other object in a finalizer, it could have been finalized before your object.

    The finalizer of your TcpClient will be called by the garbage collector, so let him do.

    The pattern in Dispose is :

    protected virtual void Dispose(bool disposing)
    {
       if (disposing)
       { 
          // dispose managed resources (here your TcpClient)
       }
    
       // dispose your unmanaged resources 
       // handles etc using static interop methods.
    }