Use the using statement to automatically call Dispose in C#

Some objects take up important resources and only free them when they are destroyed. Because of the weird way C# implements non-deterministic finalization, you don't know when those objects are actually destroyed (they may not be until the program ends) so you don't know when the resources are freed.

Many classes that use scarce resources provide a Dispose method to free their resources. If an object has a Dispose method, you should always call it when you are done with the object. Unfortunately you may forget to do this. It can also be tricky to call Dispose in odd cases, for example when control jumps out of the code due to an exception.

To solve these problems, most of these classes also implement the IDispose interface and that lets you use them in a using statement. The using statement automatically calls the object's Dispose method when the using block ends, even if it ends because of an exception.

This example uses the following code to draw a diamond with a custom Pen. The Pen class uses scarce graphics resources that you should free as soon as possible so the code uses a using statement to ensure that Dispose is called.

// Draw something.
private void Form1_Paint(object sender, PaintEventArgs e)
{
// Clear.
e.Graphics.Clear(this.BackColor);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

// Make points to draw a diamond.
Point[] points =
{
new Point((int)(this.ClientSize.Width / 2), 0),
new Point(this.ClientSize.Width, (int)(this.ClientSize.Height / 2)),
new Point((int)(this.ClientSize.Width / 2), this.ClientSize.Height),
new Point(0, (int)(this.ClientSize.Height / 2)),
};

// Make the pen.
using (Pen dashed_pen = new Pen(Color.Red, 10))
{
dashed_pen.DashStyle = DashStyle.Dot;
e.Graphics.DrawPolygon(dashed_pen, points);
}
}

The simplest syntax for the using statement is as shown in this code: declare and initialize the object in the using statement. When the using block ends, the variable is Disposed.

The Graphics and Brush classes also have Dispose methods so you should use using for them as well.

Note that you should not call Dispose on an object that you will need to use later. Sometimes knowing whether you need the object can be tricky. For example, the Bitmap class also has a Dispose method but if you display it in a PictureBox or some other control, then the program needs to use the Bitmap to redraw the control. Your code doesn't need it but the program does and if you call its Dispose method, then the program crashes the next time it needs to redraw the control.

The moral is: always use using if you can.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.