什么时候需要 Dispose? [英] When is Dispose necessary?

查看:63
本文介绍了什么时候需要 Dispose?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你有这样的代码时:

Bitmap bmp = new Bitmap ( 100, 100 );
Graphics g = Graphics.FromImage ( bmp );

Pen p = new Pen ( Color.FromArgb ( 128, Color.Blue ), 1 );
Brush b = new SolidBrush ( Color.FromArgb ( 128, Color.Blue ) );

g.FillEllipse ( b, 0, 0, 99, 99 );    
g.FillRegion ( b, pictureBox1.Region );

pictureBox1.BackColor = Color.Transparent;
pictureBox1.Image = bmp;

钢笔和画笔必须扔掉吗?bmp和g呢?

Do you have to dispose the pen and brush? What about bmp and the g?

我的主要问题是,如果这些要手动处置,为什么不在它们超出范围后立即处置?如果您不手动处理它们,会发生这种情况吗?是延迟导致人们手动执行此操作吗?

My main question is, if these were to be disposed manually, why don't they get disposed as soon as they get out of the scope? Is that what would happen, if you didn't dispose them manually? Is it the delay that makes people do this manually?

推荐答案

是的,你必须处理它们——不仅仅是笔和画笔,还有 BitmapGraphics.

Yes, you have to dispose them - not just pen and brush, but also Bitmap and Graphics.

它们在超出范围时不会被释放,因为变量本身是引用,而不是对象,并且 C# 编译器不知道所有权是否仍然属于这些引用(例如 FillEllipse 理论上可以记住它给出的引用,并在以后尝试使用它 - 请记住,语言编译器没有任何特殊的库语义知识!).

They don't get disposed when they're out of scope because the variables themselves are references, not objects, and C# compiler doesn't know whether the ownership still belongs to those references or not (e.g. FillEllipse could, in theory, remember the reference it's given, and try to use it at some later moment - remember that language compiler doesn't have any special knowledge of library semantics!).

如果您想表明所有权仅限于该范围,请使用 using 语句:

If you want to indicate that ownership is restricted to that scope, you use the using statement:

using (Bitmap bmp = new Bitmap ( 100, 100 ))
using (Graphics g = Graphics.FromImage ( bmp ))
using (Pen p = new Pen ( Color.FromArgb ( 128, Color.Blue ), 1 ))
using (Brush b = new SolidBrush ( Color.FromArgb ( 128, Color.Blue ) ))
{
    g.FillEllipse ( b, 0, 0, 99, 99 );    
    g.FillRegion ( b, pictureBox1.Region );
}

这将使编译器根据需要自动插入对 Dispose 的调用,确保一旦离开相应的 using 范围(无论正常情况下,通过控制转移),所有对象都被释放例如 returnbreak,或异常).

This will make the compiler insert calls to Dispose automatically as needed, ensuring that all objects are disposed once the corresponding using scope is left (whether normally, by control transfer such as return or break, or an exception).

如果你有 C++ 背景,C# 中的 using 直接类似于 const std::auto_ptr,只不过这里是一种语言构造,只能用于局部变量(即不用于类字段).

If you come from a C++ background, using in C# is directly analogous to a const std::auto_ptr, except that it's a language construct here, and can only be used for local variables (i.e. not for class fields).

这篇关于什么时候需要 Dispose?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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