Ramon Smits

Tell me your secrets and i'll tell you mine

Recent Posts

Tags

Community

Email Notifications

Patterns & Practices / Guidelines

EntLib

Nant

Blogs that I monitor

Archives

Cool finalizer assert trick

I just saw a cool trick done in a finalizer of a class. When a class implements IDisposable then its creator needs to call Dispose when it is finishen. Lots of developers forget this and that usually results in system resources that are locked until the garbage collector thinks its time to do its work.

The code construction I saw was:

~MyCoolClass()
{
    System.Diagnostics.Debug.Assert(false);
    Dispose(false);
}   

I have never thought of doing this but it makes sense to just add a assert to a finalizer to get notified that you didn’t dispose the object. The finalizer will never be called if it would because of the GC.SuppressFinalize(this); statement that should be done when calling IDisposable.Dispose on the object.

It could be that you are getting this in a service and then this doesn’t make any sense but then you could just log an error instead.

Posted: Sun, Apr 12 2009 3:24 PM by Ramon Smits | with no comments |
Filed under: ,
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Please add 3 and 2 and type the answer here: