Cool finalizer assert trick

By ramon
April 12, 2009
0

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.

Comments: 0

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Recent Posts
  • Recent Comments
  • Archives
  • Categories
  • Meta