Jakew
Consulting, hacking, and motorcycles

Trivia – IDisposable and using clauses

Tuesday, 11 December 2007 21:43 by jakew

This is another of the trivia bits that I hate. I have nothing against IDisposable. It just happens that because of my coding practices it doesn’t really help.

Back in the good old days (and they were good) we coded in C++. We wrote our code in the rain and used a shovel for our desk. Trudged 2 miles uphill to find the compiler and another 2 miles uphill to get back to the debugger. C++ leaves memory management to the developer. You get to allocate your objects out on the heap and you get to free them. Get it wrong and you get to spend long hours with the debugger trying to figure out why everybody hates you. Today the .NET runtime takes care of that for us. You throw object around and magically behind the scenes the GC comes along and cleans up the mess when you’re done with the object.

However, the Garbage collector only knows how to clean up memory. If you object happens to have a file handle open the GC won’t close it automatically. But if your object provides a finalizer the GC will call it to let your object clean itself up before the memory is cleaned. The trick is – you can’t trust the GC to stay on schedule. .NET rocks because it’s fast. Cleaning up memory is slow so the GC doesn’t run that often. So using a finalizer to close your file handles is probably not a great strategy. What do you do?

You implement IDisposable. IDisposable is a way to tell the world to call Dispose on your object when done. To make things easier C# provides the using clause which will automatically call Dispose on your object on the way out. Greatness. Really?

Here’s the thing, in my opinion this is sort of dumb. My practice is to explicitly open, use and close the resource in one place. To me, spreading the resource utilization across several methods is just asking for trouble (why else do we have an IDisposable?). I came by this practice from using MTS/COM+ where it was drilled in to my head to release things as quickly as possible.

As a result of my practice the big reason I know about IDisposable is because it comes up during interviews. Otherwise to me it’s pretty useless.

Categories:  
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed