Not logged in - Login

Implement Dispose() properly

The following illustrates how to properly implement the Dispose() function for a class which has the IDisposable interface:

public class MyClass : IDisposable
{
   public void Dispose()
   {
      this.Dispose(true);

      // Call SupressFinalize in case a subclass implements a finalizer.
      // Requests that the system not call the finalizer for the specified object.
      GC.SuppressFinalize(this);
   }

   private bool m_bDisposed = false;
   protected virtual void Dispose(bool disposing)
   {
      // If you need thread safety, use a lock around these  
      // operations, as well as in your methods that use the resource. 
      do
      {
         // if the object is already disposed, get out now.
         if (this.m_bDisposed) break;

         if (disposing)
         {
            // dispose of all local objects here.
         }

         // Set flag to indicate that the instance has been disposed.
         this.m_bDisposed = true; 

      } while (false);
   }
}