当你处理GDI +的资源? [英] When do you dispose GDI+ resources?

查看:104
本文介绍了当你处理GDI +的资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多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.

这篇关于当你处理GDI +的资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆