IDisposable alerts

Types that implement IDisposable usually do so for a reason. They probably consume resources that should be released as early as possible.

In a recent project, I came across a very neat idea. In the destructor/finalizer/finaliser of your IDisposable type, do something to alert the consumer that you’re being collected by the Garbage Collector and hence you haven’t been disposed of correctly.

But how does this type know it’s not been disposed correctly? Well, if you follow the IDisposable pattern to the letter (described in the excellent book Effective C# (Item 18), and about 3,000 places around t’internet), in your Dispose method, you’ll call GC.SupressFinalize(this); meaning the Garbage Collector won’t call your finalizer. So if you ever end up in the finalizer, the naughty user hasn’t called Dispose or hasn’t put the construction of your type in a using block.

There’s two bits to this

The constructor:

public MyResourceHungryType( )
_stackTrace = new StackTrace( ) ;

The finalizer:

~MyResourceHungryType( )
Debug.WriteLine( _stackTrace.ToString( ) ) ;

Then, if the finalizer is ever called, you’ll get a call stack printed up to the point where you created this type – something like:

at Namespace.MyResourceHungryType..ctor()
at Namespace.MyType.DoSomething()
at SomeNamespace.SomeMethod()



Since you've made it this far, sharing this article on your favorite social media network would be highly appreciated 💖! For feedback, please ping me on Twitter.

Leave a comment

Comments are moderated, so there may be a short delays before you see it.