当你处理GDI +的资源?当你、资源、GDI

2023-09-03 06:41:13 作者:背影挥之不去ゝ

许多GDI +类实现IDisposable,但我不知道什么时候我应该调用Dispose。很明显,因为我与或静态方法,如 Graphics.CreateGraphics 创建实例。但怎么样的对象,通过属性获取返回?我经常写code是这样的:

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;

我应该处理 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;
}

我找不到有关,在MSDN什么,文档中的样本似乎从来没有处理任何事情。

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

推荐答案

在一般情况下,如果类是的IDisposable ,你必须调用。处置方法时不需要的对象。

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

此外,MSDN库说:

修改返回的区域对象   通过剪辑属性不影响   随后的拉伸与图形   目的。要更改剪辑区域,   替换剪辑属性值与   新的区域对象。

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.

这意味着,你必须配置 oldRgn

Which means, you MUST dispose oldRgn.

 
精彩推荐
图片推荐