Introduction
This is yet another article on the use of the interface class IDisposable
. Essentially, the code that you are going to see here is no different than the code on MSDN or these two excellent articles:
Garbage Collection in .NET by Chris Maunder:
http://www.codeproject.com/managedcpp/garbage_collection.asp
General Guidelines for C# Class Implementation by Eddie Velasquez:
http://www.codeproject.com/csharp/csharpclassimp.asp
What's different is that this article illustrates the functional aspects of:
- the destructor
- the
Dispose
method
- memory allocation
- garbage collection issues
In other words, there's lots of articles showing how to implement IDisposable
, but very few demonstration of why to implement IDisposable
.
How To Implement IDisposable
The salient features of the code below are:
- Implement the
Dispose
method of the IDisposable
interface
- Only
Dispose
of resources once
- The implementing class requires a destructor
- Prevent the GC from disposing of resources if they've already been manually disposed
- Track whether the GC is disposing of the object rather than the application specifically requesting that the object is disposed. This concerns how resources that the object manages are handled.
And here's a flowchart:
Note two things:
- If
Dispose
is used on an object, it prevents the destructor from being called and manually releases managed and unmanaged resources.
- If the destructor is called, it only releases unmanaged resources. Any managed resources will be de-referenced and also (possibly) collected.
There are two problem with this, which I'll come back to later:
- Using Dispose does not prevent you from continuing to interact with the object!
- A managed resource may be disposed of, yet still referenced somewhere in the code!
Here's an example class implementing IDisposable
, which manages a Image
object and has been instrumented to illustrate the workings of the class.
public class ClassBeingTested : IDisposable
{
private bool disposed=false;
private Image img=null;
public Image Image
{
get {return img;}
}
public ClassBeingTested()
{
Trace.WriteLine("ClassBeingTested: Constructor");
}
~ClassBeingTested()
{
Trace.WriteLine("ClassBeingTested: Destructor");
Dispose(false);
}
public void Dispose()
{
Trace.WriteLine("ClassBeingTested: Dispose");
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposeManagedResources)
{
if (!this.disposed)
{
Trace.WriteLine("ClassBeingTested: Resources not disposed");
if (disposeManagedResources)
{
Trace.WriteLine("ClassBeingTested: Disposing managed resources");
if (img != null)
{
img.Dispose();
img=null;
}
}
Trace.WriteLine("ClassBeingTested: Disposing unmanaged resouces");
disposed=true;
}
else
{
Trace.WriteLine("ClassBeingTested: Resources already disposed");
}
}
public void LoadImage(string file)
{
Trace.WriteLine("ClassBeingTested: LoadImage");
img=Image.FromFile(file);
}
}
Why Implement IDisposable?
Let's put this class into a simple GUI driven test fixture that looks like this:
and we'll use two simple tools to monitor what's going:
The test is very simple, involving loading a 3MB image file several times, with the option to dispose of the object manually:
private void Create(int n)
{
for (int i=0; i<n; i++)
{
ClassBeingTested cbt=new ClassBeingTested();
cbt.LoadImage("fish.jpg");
if (ckDisposeOption.Checked)
{
cbt.Dispose();
}
}
}
The unsuspecting fish, by the way, is a Unicorn Fish, taken at Sea World, San Diego California:
Observe what happens when I create 10 fish:
Ten fish took up 140MB, (which is odd, because the fish is only a 3MB file, so you'd think no more than 30MB would be consumed, but we won't get into THAT).
Furthermore, observe that the destructors on the objects were never invoked:
If we create 25 fish, followed by another 10, notice what happens to the time it takes to haul in the fish, as a result of heavy disk swapping:
This is now taking two seconds on average to load one fish! And did the GC start collecting garbage any time soon? No! Conversely, if we dispose of the class as soon as we're done using it (which in our test case is immediately), there is no memory hogging and no performance degradation. So, to put it mildly, it is very important to consider whether or not a class needs to implement the IDispose
interface, and whether or not to manually dispose of objects.
Behind The Scenes
Let's create one fish and then force the GC to collect it. The resulting trace looks like:
Observe that in this case, the destructor was called and managed resources were not manually disposed.
Now, instead, let's create one fish with the dispose flag checked, then force the GC to collect it. The resulting trace looks like:
Observe in this case, that both managed and unmanaged resources are disposed, AND that the destructor call is suppressed.
Problems
As described above, even though an object is disposed, there is nothing preventing you from continuing to use the object and any references you may have acquired to objects that it manages, as demonstrated by this code:
private void btnRefTest_Click(object sender, System.EventArgs e)
{
ClassBeingTested cbt=new ClassBeingTested();
cbt.LoadImage("fish.jpg");
Image img=cbt.Image;
cbt.Dispose();
Trace.WriteLine("Image size=("+img.Width.ToString()+", "+img.Height.ToString()+")");
}
Of course, the result is:
Solutions
Ideally, one would want to assert or throw an exception when:
Dispose
is called and managed objects are still referenced elsewhere
- methods and accessors are called after the object has been disposed
Unfortunately (as far as I know) there is no way to access the reference count on an object, so it becomes somewhat difficult to determine if a managed object is still being referenced elsewhere. Besides require that the application "release" references, the best solution is to simply not allow another object to gain a reference to an internally managed object. In other words, the code:
public Image Image
{
get {return img;}
}
should simply not be allowed in a "managing" class. Instead, the managing class should implement all the necessary support functions that other classes require, implementing a facade to the managed object. Using this approach, the application can throw an exception if the disposed
flag is true--indicating that the object is still being accessed after it has technically been disposed of.
Conclusion - Unit Testing
The reason I went through this rigmarole is that I wanted to demonstrate the inadequacies of unit testing. For example, let us assume that the test class I described above does not implement IDisposable
. Here we have an excellent example of how a single test on a class and its functions will succeed wonderfully, giving the illusion that all is well with a program that uses the class. But all is not well, because the class does not provide a means for the application to dispose of its managed resources, ultimately causing the entire computer system to bog down in fragmented memory and disk swapping.
This does not mean that unit testing is bad. It does however illustrate that it is far from a complete picture, and unit testing applications such as NUnit could use considerable growth in order to help the programmer automate more complex forms of unit testing.
And that, my friends, is going to be the topic of the next article.
Downloading The Demonstration Project
I have intentionally left out the "fish.jpg", being 3MB in size. Please edit the code and use your own JPG if you wish to play with the code.