Geeks With Blogs
sano the super geek the endeavors of the newest professional geek at microsoft.

There was a discussion on one of the internal aliases about abiding astute design patterns, particularly when it comes to memory management. I thought this would be of interest of those of you who haven’t fallen into the habit of deterministically finalizing your objects when they’re no longer needed.

One of the strengths of the Common Language Runtime (CLR) is its memory management abilities. It spawns garbage collection threads that clean up all of the objects that are no longer in use and frees up space in the memory heap that has been allocated to them. Even though the CLR guarantees that your unused objects will be cleaned up eventually, there’s no way of knowing when or how it’ll be removed from the memory heap. Theoretically, this could be years from the time that the object is instantiated.

There’s no good reason not to deterministically clean up your objects. Not only is it excellent programming practice, but you’re able to ensure that the object and all of the components that it encapsulates are being cleaned up immediately.

You can deterministically finalize any object that implements the IDisposable interface by invoking its Dispose() method. If you use C# you have the advantage of the using statement which allows you to define a scope at the end of which an object will be disposed. One of the most common examples given uses a SqlConnection object:

      using ( SqlConnection test = new SqlConnection( ... ) ) {

           

// code implementation

 

      } // SqlConnection.Dispose() is automatically invoked

 

At the end of this scope, the SqlConnection’s Dispose() method is automatically invoked and all resources held by this object are released.

 

By adopting the practice of deterministic finalization, you’ll be able to efficaciously manage your resources. Additionally, this enables you to ensure that there are no objects that contain large chunks of unmanaged resources sitting around waiting for the garbage collector to come around and clean them up.

Posted on Wednesday, January 14, 2004 5:57 PM | Back to top

Copyright © Chris Sano | Powered by: GeeksWithBlogs.net | Join free