What follows is a typical dispose pattern example:
public bool IsDisposed { get; private set; } #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!IsDisposed) { if (disposing) { //perform cleanup here } IsDisposed = true; } } ~MyObject() { Dispose(false); }
I understand what dispose does, but what I don’t understand is why you would want to call dispose(false) in the destructor? If you look at the definition it would do absolutely nothing, so why would anyone write code like this? Wouldn’t it make sense to just not call dispose from the destructor at all?
The finalizer is used as a fall-back if the object is not disposed properly for some reason. Normally the
Dispose()method would be called which removes the finalizer hookup and turns the object into a regular managed object that the garbage collector easily can remove.Here is an example from MSDN of a class that has managed and unmanaged resources to clean up.
Notice that the managed resources are only cleaned up if
disposingis true, but unmanaged resources is always cleaned up.