Possible Duplicate:
Will the Garbage Collector call IDisposable.Dispose for me?
I have a Class which has some unmanaged resources. My class implements the IDisposable
interface and releases the unmanaged resources in the Dispose()
method. Do I have to call the Dispose()
method or will it be automatically called somehow? Will the Garbage Collector call it?
Dispose()
will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable
provides a way for users of your class to release resources early, instead of waiting for the garbage collector.
The preferable way for a client is to use the using
statement which handles automatic calling of Dispose()
even if there are exceptions.
A proper implementation of IDisposable
is:
class MyClass : IDisposable
{
private bool disposed = false;
void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!disposed)
{
if(disposing)
{
// Manual release of managed resources.
}
// Release unmanaged resources.
disposed = true;
}
}
~MyClass() { Dispose(false); }
}
If the user of the class calls Dispose()
the cleanup takes place directly. If the object is catched by the garbage collector, it calls Dispose(false)
to do the cleanup. Please note that when called from the finalizer (the ~MyClass
method) managed references may be invalid, so only unmanaged resources can be released.