главная продукты downloads форум тех. поддержка

 

Главная страница

GDI+ FAQ: Disposing of GDI+ resources

You will often see the following in C# or VB code...

 

myGraphicsObject.DrawLine(new Pen(Color.Black,1), 0, 0, 10, 10)

 

The Pen object in this case is created inline and never disposed of. In old-style GDI, this was a recipe for disaster because the resources associated with GDI pens and brushes were finite and could leak, causing the system to eventually freeze up.

 

GDI+ is still an unmanaged technology but .NET provides us with managed wrappers that are lifetime managed by the Garbage Collector. This means that when the pen object goes out of scope, it will be marked for garbage collection and eventually reclaimed by the system, freeing up its resources as it goes.

 

This kind of technique is fine for quick demos and so on but if you're serious about your graphics you should behave nicely and preemptively dispose of GDI+ objects when you're done with them.

 

Explicitly disposing of an object frees its unmanaged resources and allows them to be recycled more quickly and efficiently.

 

The proper usage is to create, use and dispose of an item. in the right place. For example...

 

void override OnPaint(PaintEventArgs e)

{

        Pen p=new Pen(Color.Black,1);

        e.Graphics.DrawLine(p,0,0,10,10);

        p.Dispose();

}

 

If your application uses a lot of pens or brushes you can manage them by assigning them when the application first runs and disposing of them when the application closes during the Dispose method.

 

Back to the GDI+ FAQ

 

e-mail:

 

bousoft@mail.ru