Me, Myself and IDisposable

by Matt 10. January 2007 06:00

Yep. It's the return of the punny titles. Live with it.

This topic came up at work. Plenty has already been written about IDisposable, but that didn't stop me.

.net does not have deterministic resource management built in. In other words, by default, you have no idea when your resources will get reclaimed. If you open a file, it sits around, open, until the file object is garbage collection. You don't know when that will be. It should be obvious that this can cause problems.

Of course, for a file object, you can just add a Close method, and make sure you call it when you're done with the file. .net generalises this idea with the IDisposable interface. It defines a method, Dispose(), that tells the object to clear up whatever resources it has (the file gets closed).

But it's a convention - you have to call Dispose in your code. C# makes it easy with the "using()" statement. Any object created in the brackets of the using statement will have IDisposable.Dispose() called on it. at the end of the braces, even if an exception is thrown. We now have deterministic resource management. Hurrah!

So, when do you use it? The simple answer is any time a class implements IDisposable, you wrap it in a "using" statement. Don't try and roll your own - just use "using" (you'll probably forget to handle exceptions. And if you do, you've just implemented what using already does - try/finally).

And when do you implement it? If you handle any unmanaged resources (say you're using p/invoke to talk to an OS routine that handles resources, e.g. memory mapped files) you should implement IDisposable and clear those resources as soon as you can. If your class holds member level references to other classes that implement IDisposable, you should implement it and call Dispose on these references.

But what about types such as MemoryStream? It's not dealing with unmanaged resources - only memory. It implements IDisposable because it's base class implements it. Obviously FileStream needs to implement it because it's dealing with a file resource. Again, the answer is simple - memory is a resource also. If you don't dispose of a MemoryStream, that resource is sitting around until the garbage collector kicks in. This adds memory pressure and can very easily make it look like your app is leaking. Which is never a good thing, especially if you're building server side stuff.

On a similar note, it's probably a good idea to try and avoid keeping IDisposable objects as member fields - they stay alive for the lifetime of the object, and so does that resource pressure. You really want to try and keep IDisposable objects alive for as short a time as possible - this is where "using" is really useful. And don't hand them out as properties of your class - who owns the lifetime of the object now? You really don't want to call Dispose on an object that someone else is trying to use...

How do you implement it? I'm going to point you straight to the source. Here is Microsoft's recommended pattern. Read it and understand it - it's not terribly obvious at first read, and shows that this kind of deterministic cleanup should really have been more of a platform (or at least a more tightly integrated compiler) feature - this interface is not really pit of success territory. (Incidentally, the second version of managed C++ gets it right.)

And of course, it's complicated by the Finalizer. This is a method that's very much like Dispose, but it's what allows you to clean up unmanaged resources when someone forgets to call Dispose. If your object gets garbage collected and Dispose hasn't been called, you get added to a list and a background thread will eventually call your Finalizer. You can only clean up unmanaged resources here - any other unmanaged object you have a reference to might already have been garbage collected. Finalizing is very costly - you don't want objects to get onto the finalizer queue. Always use "using"!

This post brought to you by the word "deterministic" and the American spelling of finalise.


Comments (23) -

best suv 2011
best suv 2011
7/20/2011 10:37:03 PM #

Hi, just required you to know I he added your website to my Google bookmarks due to your layout. But seriously, I consider your net web-site has 1 in the freshest theme I??ve came across. It extremely helps make studying your blogging site significantly easier.


Rosario Carello
Rosario Carello United States
1/15/2016 6:24:08 AM #

Congrats! This is such a great website, I know it will translate well into book form. Which is AWESOME!


Walter Rigsbee
Walter Rigsbee United States
1/15/2016 6:44:25 AM #

Let me be the first to say: Congrats, Neil! I've been following this site from day one, and have loved every single day of awesomeness that it has delivered. You deserve all the success coming your way. Keep it up!AWESOME!


Cornelius Styborski
Cornelius Styborski United States
1/15/2016 8:54:25 AM #

Congratulations, Neil! I love this site and I know I'll love the book. Christmas, birthdays, Father's Day 2010  check!


Una fuente oficial del servicio secreto asegura que no han podido confirmar que sus electrones libres” intentaron enriquecerse con el caso. Desde entonces, l995, los dos hermanos se fueron de España y esfumaron en este paraíso fiscal en el corazón de Europa. Gérard Reuter, antiguo presidente de la Cámara de Cuentas de Luxemburgo suspendido en 1999 a causa de un escándalo, trabajó para el servicio secreto del Gran Ducado y vivía en uno de los apartamentos del SREL.


Phyliss Mcardell
Phyliss Mcardell United States
8/25/2016 4:06:36 AM #

Truly informative. Hopefully you can discuss more on the Smart house design and technology using the recent obtainable gadget


Particia Morelli
Particia Morelli United States
2/18/2017 1:50:51 AM #

There is a mixture of reasons why people employ us as their Port Coquitlam android app development, Surrey mobile app development. From mobile internet to social networks and from mobile apps to multimedia, this mobile phone has everything you will ever need. It illustrates this old tale from the perspectives of the jackal and the lion. The bigger and much more popular the website is, the greater, and also the higher the PR will probably be. Kayak flight and hotel research application is the best way of booking tickets or hotels.


Emily Tank
Emily Tank United States
3/27/2017 3:25:04 AM #

This is a great site with some great information


Blake Haislip
Blake Haislip United States
10/7/2018 7:41:51 AM #

What’s Happening i'm new to this, I stumbled upon this I have found It positively useful and it has helped me out loads. I am hoping to give a contribution & help other customers like its helped me. Good job.


Desmond Lunsford
Desmond Lunsford United States
10/10/2018 3:49:06 PM #

Email bombs, carding guides, visa, mastercard, hacking service, fake money, Spam service, Call bombs , SMS bombs, Bitcoin stealers ! - EVERYTHING YOU NEED TO MAKE SERIOS AMOUNTS OF BITCOIN HERE - http://456bosfo4pgtbrv3.onion YOU MUST USE TOR TO ACCESS. EMAIL US AT


FineScan療程 United States
10/13/2018 7:57:32 AM #

高能聚焦量超聲波( HIFU )以物理性聚焦集中成一點, 快速穿透皮膚真皮及脂肪層面直達面部表淺肌肉腱膜系統( SMAS )層令其組織細胞分子高速磨擦 , 瞬間升溫至60 -70 度,令整個表淺肌肉腱膜系統( SMAS )受熱收縮,形成熱固化區域, 令結綈組織同時拉緊,達到拉皮防皺及美容效果。SMAZ聚焦超聲波提供了最有效的HIFU能量收緊皮膚及刺激胶原蛋白新生,提升彈性,恢復更緊緻的皮膚和更年輕的美貌。


Gerardo Horton
Gerardo Horton United States
10/15/2018 5:39:12 AM #

been very happy with


Anabel Dorn
Anabel Dorn United States
10/15/2018 6:48:26 AM #

Very happy with the results from looking good in my new jeans.


SHISEIDO 資生堂-開架式 【water in lip】Water in Lip(莓果) Water in Lip的商品介紹   SHISEIDO 資生堂-開架式,water in lip,Water in Lip(莓果) Water in Lip       


Laronda Grisby
Laronda Grisby United States
10/21/2018 12:28:25 AM #



獨家IELLIOS療程 United States
10/21/2018 6:16:19 PM #

我們採用國際及美國食品及藥物管理局FDA認可的CO2 激光儀 LUTRONICS® SPECTRA SPR, 具安全性, 準確度高 . 二氧化碳激光可安全地去除皮膚上的癦痣、肉粒、疣、老人斑等問題。此激光的幼細光束可準確及直接地將要去除的組織氧化,過程快捷,傷口細小及乾淨,對周圍的皮膚傷害減至最少。一般1-2次就可永久去除。


A-PLUS Beauty: Restylane Perlane 透明質酸高鼻 真人大解構  A-PLUS Beauty: Restylane Perlane 透明質酸高鼻 真人大解構      


Gerardo Horton
Gerardo Horton United States
12/10/2018 8:13:03 PM #

Hacking group you can trust - http://oufkrhddoiik3xoy.onion - best money I ever spent.You must use TOR browser to access.Wild hacker crew


Laronda Grisby
Laronda Grisby United States
12/11/2018 9:47:09 PM #

Got my fake money from the wild hacker crew today went to the shops straight away and passed one of them in costa coffee. Easy money was scary. http://oufkrhddoiik3xoy.onion Thats the address that will make you a fortune.Wild hacker crew


Janel Hausmann
Janel Hausmann United States
1/18/2019 3:43:58 AM #

No one can hack like the guys - Wild hacker crew http://oufkrhddoiik3xoy.onion - Sorry but the wild hacker crew are f**king awesome.Wild hacker crew


Michaela Hurst
Michaela Hurst United States
1/18/2019 2:18:32 PM #

Those Wild Hacker Crew guys are crazy. I bought the carding guide and made my money back in 12 hours. They said not to go so fast but it all worked good and I got paid. I have had 3 jobs done from them now - http://oufkrhddoiik3xoy.onion HAVE FUN & be good lmfao.Wild hacker crew


Frankie Adriance
Frankie Adriance United States
1/20/2019 10:56:13 AM #

Excellent beat ! I would like to apprentice while you amend your site, how could i subscribe for a blog website? The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast offered bright clear idea|


Rudolph Koloski
Rudolph Koloski United States
1/20/2019 1:35:45 PM #

I got this website from my friend who told me regarding this web page and now this time I am browsing this website and reading very informative articles or reviews at this place.|


Add comment

  • Comment
  • Preview


Month List


Comment RSS