Wednesday, February 6, 2008

Managing Unmanaged Resources

Submit this story to DotNetKicks

Unmanaged Resources are objects that are not garbage collected, which means that they are not reclaimed by the system when the garbage collector cleans up after you.

But are Unmanaged Resources resources outside .NET framework like DLL used through interop? No, unmanaged resources can also be database connection. It is a common mistake by programmers not to close the connection when finished working with it, in misconception that the garbage collection will close it.

So how do I identify if the object is an unmanaged resource? If the object implement the IDisposable interface it have an unmanaged resource and you need to call the IDisposable.Dispose() method to clean the objects unmanaged resource.
If you use the object in a single call you can wrap it in a using statement (http://softscenario.blogspot.com/2007/10/using-using.html), and it will call the Dispose() method for you. If you keep the object for a longer time you must support the IDisposable interface in your class, and in your implementation of the Idisposable.Dispose() call the member's IDisposable method.


Remember to look for the IDisposable interface in the classes you use in your development. You will be surprised how many classes that do.

1 comment:

FJGamer - RuneScape Dragoons animator said...

In the Linux world, things are much more secure and stable.