Monday, June 11, 2012

Proper use of the IDisposable interface

I know from reading the MSDN documentation that the "primary" use of the IDisposable interface is to clean up unmanaged resources.

To me, "unmanaged" means things like database connections, sockets, window handles, etc. But, I've seen code where the Dispose method is implemented to free managed resources, which seems redundant to me, since the garbage collector should take care of that for you.

For example:

public class MyCollection : IDisposable
private List<String> _theList = new List<String>();
private Dictionary<String, Point> _theDict = new Dictionary<String, Point>();

// Die, you gravy sucking pig dog!
public void Dispose()
_theList = null;
_theDict = null;

My question is, does this make the garbage collector free memory used by MyCollection any faster than it normally would?

edit : So far people have posted some good examples of using IDisposable to clean up unmanaged resources such as database connections and bitmaps. But suppose that _theList in the above code contained a million strings, and you wanted to free that memory now , rather than waiting for the garbage collector. Would the above code accomplish that?

Source: Tips4all

No comments:

Post a Comment