Disposing my crap…
[UPDATED] OK, ignore this post and read the IDispose Guidelines. This is a very lengthy post but well worth the read!!!
When using unmanaged resources, you have 2 options cleaning up after using the resources:
1. Override the Finalize.
Pro: Finalize() is called by the GC… just implement it and be sure that the GC will call it
Cons: Performance hit
2. Implement IDisposable
Pro: Lightweight and easy to implement
Cons: Developer must remember to call Dispose() (And we are only human)
Why not combine the 2?
public class MyUnmanagedResource : IDisposable
{
~MyUnmanagedResource()
{
// Cleanup resources
}
public void Dispose()
{
// Cleanup resources
GC.SuppressFinalize(this);
}
}
Now this might seem a little excessive but I have a Dispose() that can be called by the developer to do the cleanup (This will also ensure that the finalize never happen by calling GC.SuppressFinalize(this)) but if he “forgets” to call the Dispose(), the finalize does the cleanup!!
Over-engineered, maybe! But it is SAFE…