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:
- A
publicnon-virtual (NonInheritablein Visual Basic) IDisposable.Dispose implementation that has no parameters. - A
protected virtual(Overridablein Visual Basic)Disposemethod 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;
}
}