2

Does anyone have a good articles or tutorial on correctly using dispose and IDisposable. I am trying to explain this to some junior dev and wanted to get some extra material, examples, etc.

4 Answers 4

6

A good place to start is this MSDN article by Shawn Farkas http://msdn.microsoft.com/en-us/magazine/cc163392.aspx. The definitive article is by Joe Duffy at http://www.bluebytesoftware.com/blog/2005/04/08/DGUpdateDisposeFinalizationAndResourceManagement.aspx with some follow-up in http://www.bluebytesoftware.com/blog/2008/02/18/IDisposableFinalizationAndConcurrency.aspx

1

Many older sources of advice on this imply that IDisposable is linked in some way to finalizers. Pay very close attention to the comments of Herb Sutter on this subject. Do NOT leap to the conclusion that you need to write a finalizer if you implement IDisposable, to "make sure that Dispose runs eventually in case the client forgets to call it". This is generally not the case. A class may implement IDisposable so that it can make various calls on managed objects that it owns, e.g. Dispose those objects in turn. This is absolutely pointless to do from a finalizer because finalizers can't reliably access other managed objects. Also anything a finalizer does must be capable of being called from any thread. Finalizers are a very obscure advanced thing, whereas IDisposable is a simple pattern that ought to be ubiquitous. And the advent of SafeHandle changes the situation further.

0

Here's my one. :-)

http://www.blackwasp.co.uk/IDisposable.aspx

1
  • 1
    "If you create a class that does not use unmanaged resources then you should not implement IDisposable." Where do people get that idea from? Oct 22, 2008 at 22:33
0

Tell them to always use the using statement on disposable objects.

using (MyDisposable obj = new MyDisposable())
{
  obj.some_stuff();

} //obj is disposed here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.