Tuesday, January 29, 2013

The Garbage Collector does not call the Dispose() method!

If you have ever wondered if the Garbage Collector calls the Dispose method on objects that implement the IDisposable interface, the answer is no.

It calls the Finalize method, which does nothing by default. If you have any unmanaged or additional resources that you want freed or released after the lifetime of an object, you must call the properly overriden Dispose method. I won't get in details on the Dispose pattern or anything like that, not on this post. Maybe on the future...

Anyway, this caught my attention because we had lots of objects that used unmanaged resources and they were not being freed, causing some memory leaks. The Dispose method was correctly implemented on these objects but the only thing is that it wasn't being called at all!

So my suggestion is that you always use try-catch-finally blocks or using blocks when dealing with disposable objects, specially when they use unmanaged resources. Make sure that you always call the Dispose method.

Simple example of a Foo class that uses some unmanaged resources inside of an using block, assuming that the Dispose method effectively frees any resources that the object uses:

using(var disposableFoo = new Foo())
    // Use your disposable foo

No comments:

Post a Comment