OO/.NET – Disposing of unmanaged resources

There are two areas of GC to be aware of. First, GC does not happen right away. If you aren’t proactive about removing objects, they stay in memory waiting for GC to pick them up (destroy them). And GC has its own algorithm for figuring out how to do so, so you never know exactly when that will be, or if soon enough to save your app from high load. This is where calling Dispose() on a object comes in.

For today’s subject, I also want to mention releasing unmanaged resources efficiently, in case your caller code forgets to Dispose of them, or can’t wait for GC. These resources (such as window handles, etc.) are not automatically disposed of. In a sense, they get orphaned as their owner (your managed class) has disappeared. The garbage collector doesn’t know how or want to find all such resources and/or how to destroy them as well, nor should it have to; GC is managed, it wouldn’t know unmanaged resources exist. If it had to worry about not only the base object you asked it to collect, but also objects beyond that one, GC would become even more taxed and complex than it already is.

Here’s a very good article on MSDN showing how to properly code classes that use such resources and how to efficiently release or recycle system resources inside the application.