Geeks With Blogs

News View David Douglass's profile on LinkedIn

My Presentations
David Douglass .NET on My Mind

Here's what I've learned in a recent fight with a nasty object disposal bug.

Every .NET developer needs to understand object disposal.  Start with DG Update: Dispose, Finalization, and Resource Management for a complete discussion of the topic.

Carefully implement the pattern.  Here's the bug I had to deal with:

protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { // dispose of managed objects // dispose of unmanaged resources } disposed = true; } }

Both the managed objects and unmanaged resources were being disposed of only when disposing was true.  The code should have been:

protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { // dispose of managed objects } // dispose of unmanaged resources disposed = true; } }

 

What this bug does is interfere with finalization.  All of an object's resources that haven't already been released should be during finalization.  But, because the unmanaged resources were disposed of only when disposing was true, nothing was disposed of during finalization.

What's unusual about this bug is that you may never notice it or it may cause you to exhaust a resource and prevent your application from running.  If every disposable object is disposed of, then it doesn't matter that finalization doesn't do anything because there wouldn't be anything to do.  But what if you forget to call Dispose?  In that case the unmanaged resources will never be disposed of and you'll have a classic C++ style leak on your hands.

Whenever possible, use a using statement to ensure object disposal.

Note that there was a huge change between Visual C++ 2003 and Visual C++ 2005 regarding object disposal.  See Changes in Destructor Semantics for details.

Posted on Sunday, May 4, 2008 11:52 AM | Back to top


Comments on this post: Observations on .NET Object Disposal

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © David Douglass | Powered by: GeeksWithBlogs.net