Wednesday, March 19, 2008

Dispose(), Destructor/Finalizer

Destructors are called by GC (non-deterministic) ~ClassName() in C# & Finalize() method in VB.NET when GC determines it is time for garbage collection.
Not the best place to put cleanup code.
Ex: open a database connection and put the cleanup code in the Destructor. That DB connection might stay open for the life of the entire application. Not good!

Dispose() method:
A better place to put cleanup code.
Mostly used to cleanup unmanaged resources.
using{} statement automatically calls the Dispose() before exiting.
Recommended to be called only if the object is resource intensive.

References:
http://www.dotnetspider.com/qa/Question1450.aspx

No comments: