Dispose vs. finalizers
suggest changeImplement Dispose (and implement IDisposable) so unmanaged or other expensive resources can be released as soon as the object is no longer used. Nothing guarantees that Dispose will be called. A finalizer is also not guaranteed to run: the process can exit first, and the garbage collector never promises to finalize every unreachable object.
One scenario is a program calling Dispose() on objects it explicitly creates:
private void SomeFunction()
{
// Initialize an object that uses heavy external resources
var disposableObject = new ClassThatImplementsIDisposable();
// ... Use that object
// Dispose as soon as no longer used
disposableObject.Dispose();
// ... Do other stuff
// The disposableObject variable gets out of scope here
// The object will be finalized later on (no guarantee when)
// But it no longer holds the heavy external resource after it was disposed
}
Another scenario is declaring a class to be instantiated by the framework. In this case the new class usually inherits a base class, for instance in MVC one creates a controller class as a subclass of System.Web.Mvc.ControllerBase. When the base class implements IDisposable interface, this is a good hint that Dispose() would be invoked properly by the framework - but again there is no strong guarantee.
Dispose is not a substitute for a finalizer. Use them for different purposes:
- A finalizer is a last resort for unmanaged resources (handles, native memory) if
Disposewas never called. It does not free managed memory; the garbage collector does that. Disposereleases those resources as soon as they are no longer needed. CallGC.SuppressFinalize(this)fromDisposewhen the class also has a finalizer, so the object is not finalized after it has already been cleaned up.