Implement a Dispose method

Implementing the Dispose method is primarily for releasing unmanaged resources. When working with instance members that are IDisposable implementations, it’s common to cascade Dispose calls.

Dispose() and Dispose(bool)

The IDisposable interface requires the implementation of a single parameterless method, Dispose. Also, any non-sealed class should have an additional Dispose(bool) overload method to be implemented:

  • public non-virtual (NonInheritable in Visual Basic) IDisposable.Dispose implementation that has no parameters.
  • protected virtual (Overridable in Visual Basic) Dispose method whose signature is: 
protected virtual void Dispose(bool disposing)
{
}

Important : The disposing parameter should be false when called from a finalizer, and true when called from the IDisposable.Dispose method. In other words, it is true when deterministically called and false when non-deterministically called.

The Dispose() method

public void Dispose()
{
   // Dispose of unmanaged resources.
   Dispose(true);
   // Suppress finalization.
   GC.SuppressFinalize(this);
}

The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects’ Object.Finalize override. Therefore, the call to the SuppressFinalize method prevents the garbage collector from running the finalizer. 

 public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }
private void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                // clear unmanaged resources. 
                if (disposing)
                {
                }

                this.disposed = true;
            }
        } 

Published by codeblogforfun

Coder, blogger, traveler

Leave a comment

Design a site like this with WordPress.com
Get started