开发者

When do you dispose GDI+ resources?

开发者 https://www.devze.com 2022-12-22 02:38 出处:网络
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 object

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 ret开发者_C百科urned 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消