C# Tips: Keep it Short, Get it Done - Implementing IDisposable
(Page 2 of 4 )
Generally speaking, you do not need to worry about disposal. The main exception, however, is when you are using an unmanaged resource – like a database connection or a flat file – or any other resource, except for memory. The .NET framework provides the “IDisposable” interface for this purpose. Since there is no way to guarantee that the “Dispose()” method gets called, it is considered a best practice to wrap a call to the “Dispose()” method in an objects finalizer (destructor).
When the garbage collector runs, all objects with a finalizer are left in memory and have their finalizers executed. Objects without finalizers are simply deleted from memory – which is where unmanaged resources pose the potential for leakage.
Here is the “IDisposable” interface:
public interface IDisposable
{
void Dispose();
}
The following code illustrates the basic usage of the “IDisposable” interface.
public class MyClass : IDisposable
{
private bool _isDisposed = false;
~MyClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(true);
}
protected virtual void Dispose(bool isDisposing)
{
if (_isDisposed)
return;
if (isDisposing)
{
// Free managed resources
}
// Free unmanaged resources here
_isDisposed = true;
}
}
You may be wondering why there is a virtual overloaded version of the “Dispose()” method in the code above. We created the virtual method to be used as a hook for derived classes to call the base classes disposal method, thus making sure that all resources are properly released.
The most important thing to remember when implementing disposal is that you should only be freeing resources in the “Dispose()” method, nothing else. Do not call any object methods or create references to the current object or do anything else that could effectively resurrect that object. Remember, you never know in what order objects will be disposed, so you may end up working on an object that is already disposed or finalized. Doing that puts the object in question back into a global list of objects, but the garbage collector will not know to dispose of it again because it’s already been done!
Next: Using “using” >>
More C# Articles
More By David Fells