When do you dispose GDI+ resources?

北慕城南 提交于 2019-12-12 08:28:03

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/2361931/when-do-you-dispose-gdi-resources

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!