Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you dispose GDI+ resources?

Tags:

.net

gdi+

Many GDI+ classes implement IDisposable, but I'm not sure when I should call Dispose. It's clear for instances I create with new or static methods like Graphics.CreateGraphics. But what about objects that are returned by property getters? I often write code like this:

var oldRgn = g.Clip;
using (var rectRegion = new Region(rectangle))
{
    g.Clip = rectRegion;
    // draw something
}
g.Clip = oldRgn;

Am I supposed to dispose oldRgn after that? My memory profiler tells me there are undisposed instances if I don't. And looking at the implementation in reflector at least confirms that the getter apparently creates a new instance every time it's invoked:

// Graphics.Clip code from Reflector:
public Region get_Clip()
{
    Region wrapper = new Region();
    int status = SafeNativeMethods.Gdip.GdipGetClip(new HandleRef(this, this.NativeGraphics), new HandleRef(wrapper, wrapper.nativeRegion));
    if (status != 0)
    {
        throw SafeNativeMethods.Gdip.StatusException(status);
    }
    return wrapper;
}

I couldn't find anything about that in the MSDN, and the samples in the documentation never seem to dispose anything.

like image 922
Niki Avatar asked Mar 02 '10 09:03

Niki


1 Answers

In general, if the class is IDisposable, you must call the .Dispose method when the object is not needed.

Also, the MSDN library says:

Modifying the Region object returned by the Clip property does not affect subsequent drawing with the Graphics object. To change the clip region, replace the Clip property value with a new Region object.

Which means, you MUST dispose oldRgn.

like image 51
Kerido Avatar answered Sep 18 '22 15:09

Kerido