Joey said:
I was wondering what is the correct way of cleaning up?
Class instances often encapsulate control over resources that are not
managed by the runtime, such as database connections and similar. You
can provide implicit control over how these resources are managed by
implementing a destructor in the class. The garbage collector calls this
method at some point after there are no longer any valid references to
the object.
If an external resource is scarce or expensive, you might want to
provide the ability to explicitly release these resources before the
garbage collector frees the object. To provide explicit control,
implement the IDisposable interface.
If you implement IDisposable, you should provide implicit cleanup using
a destructor.
Here is an example of a best-practice implementation of IDisposable:
public class MyClass : IDisposable {
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
// Free other managed objects.
}
// Free unmanaged objects and set large fields to null.
}
~MyClass() {
Dispose (false);
}
}
For more info on when you use destructors and when to implement the
IDisposable interface see
http://msdn.microsoft.com/library/d.../en-us/cpgenref/html/cpconFinalizeDispose.asp
Anders Norås
http://dotnetjunkies.com/weblog/anoras/