Cleanup is only necessary in Dot Net to release unmanaged resources. There are two types of cleanup:
· Explicit cleanup, implement IDisposable. Use this method
o To provide clients of your class a way to cleanup on demand instead of waiting for the garbage collector.
o When your class holds an indirect reference to an unmanaged resource, e.g., any managed object that has a Dispose() method.
· Implicit cleanup, implement destructor, e.g., ~ClassName(). Use this method
o When your class holds a direct reference to an unmanaged resource, e.g., a window handle.
A cleanup design pattern is laid out by Microsoft at http://msdn2.microsoft.com/en-us/library/b1yfkh5e(VS.71).aspx and is as follows:
[C#]
// Design pattern for a base class.
public class Base: IDisposable
{
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Free other state (managed objects).
}
// Free your own state (unmanaged objects).
// Set large fields to null.
}
// Use C# destructor syntax for finalization code.
~Base()
{
// Simply call Dispose(false).
Dispose (false);
}
// Design pattern for a derived class.
public class Derived: Base
{
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Release managed resources.
}
// Release unmanaged resources.
// Set large fields to null.
// Call Dispose on your base class.
base.Dispose(disposing);
}
// The derived class does not have a Finalize method
// or a Dispose method with parameters because it inherits
// them from the base class.
}