Wednesday, October 29, 2008

Dispose method

Dispose method of IDisposable interface performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. This method is used to explicitly release unmanaged resources in conjunction with the garbage collector.

When implementing this method, ensure that all held resources are freed by propagating the call through the containment hierarchy. For example, if an object A allocates an object B, and object B allocates an object C, then A's Dispose implementation must call Dispose on B, which must in turn call Dispose on C. An object must also call the Dispose method of its base class if the base class implements IDisposable.
Because the Dispose method must be called explicitly, objects that implement IDisposable must also implement a finalizer to handle freeing resources when Dispose is not called. Once the Dispose method has been called, it is unnecessary for the garbage collector to call the disposed object's finalizer. Dispose implementation calls the GC.SuppressFinalize method, to prevent automatic finalization.


 
// Implement IDisposable. Do not make this method virtual. A derived class should not be able to override this method.

public void Dispose()
{
// This object will be cleaned up by the Dispose method. Therefore, you should call GC.SupressFinalize to take this object off the finalization queue and prevent finalization code for this object from executing a second time.
GC.SuppressFinalize(this);
}

No comments: