27. September 2006
“Hi! There are no memory leaks in .Net! It has that great garbage collector everyone’s talking about! And the dispose pattern and all that”.
Not very likely that a person actually uttered this, but it’s a great start for a discussion. I’ll start mentioning some normal miss conceptions about GC, Dispose and that “stuff”:
- The garbage collector cleans up everything you keep laying around and you don’t need to worry about it.
- If you just do your cleanup in Dispose the GC will call dispose for you.
- If you really want to be sure, do your cleanup in the destructor and your home free.
Nice! Lets just do this and we can all go home… Or you can read on…:
- The garbage collector cleans up everything you don’t use anymore. That is all objects not referenced by your running program.
- If you do your cleanup in Dispose, YOU have to remember to call it! Not only that, if you use objects that have Dispose methods, you need to call them as well!
- You can do cleanup in the destructor, but it’s much more efficient to use the Dispose pattern. More on this later.
I think most of us know that the garbage collector only releases objects with no running references to it. What’s interesting though is that not everyone knows that you have to call Dispose on all objects that have a Dispose method! I can not emphasize this enough (even though I tried with bold text).
You have a gene in your body as developer to call Close methods (on file handles, data connection etc), but no one ever mentioned Dispose for you. Or you where told that the GC call Dispose for you, or something else that sounded good at the moment.