Friday, July 02, 2004

IDisposable Article Series - What's IDisposable?

IDisposable is, at the same time, one of the most simple and most important .NET interfaces. It consists of a single method, Dispose, with no parameters and returning nothing. It's declared by the .NET framework as follows:
namespace System
{
public interface IDisposable
{
void Dispose();
}
}

The goal behind IDisposable is simple: to clear any unmanaged resources allocated by a class. And what are "unmanaged resources"? First, you need to understand what are "managed resources": memory. But not any memory: only memory that the .NET framework explicitly allocated.
You probably know that the .NET framework provides you with a garbage collector (GC). While a standard technical term, I don't agree with this, I think it's not a precise term, at least in the .NET environment: there's no real "garbage collector" in .NET. What really exists is a memory recycler. Basically, you are not in control of memory deallocation and the environment takes care of this for you. Think of this as a "controlled memory leak". Your code will only ask for the GC to allocate memory and keep track of its uses, and when something triggers it (probably a combination of idle time, memory pressure and even maybe the size of your L2 cache), the GC comes in and releases all the unused memory. While this, most of the time, achieves high levels of performance and reliability, also has some very bad consequences:

If there are no predictable destructors in the .NET environment, how can API wrapper classes (e.g) Control, Bitmap, Socket or FileStream, which hold a handle to physical, costly or scarce resources, be able to automatically close handles or execute clean up code? They can't: at least, in a predictable way. So, IDisposable comes to scene, and you, the class user, are responsible for the lifetime management.

Next article part:
What are the responsibilities of the IDisposable for the class user?

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?