为什么要处置一定会很快被处置的物体? [英] Why dispose an object which will surely get disposed of soon regardless?

查看:77
本文介绍了为什么要处置一定会很快被处置的物体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个程序,例如单击按钮.

Suppose I have a procedure for e.g. a button click.

然后我创建一个Graphics对象.

And I create a Graphics object.

显然我应该将其处理掉,例如

Apparently i'm supposed to dispose of it e.g.

using(Graphics gr__=this.CreateGraphics())  {

} 

或最终在try-catch的finally中调用.Dispose().

or with calling .Dispose() in the finally of a try-catch-finally.

但是考虑到该过程将很快结束.

But considering that the procedure is going to end pretty quickly.

假设我在过程本地创建它(不是全局的,不是在使用中).但是该过程是本地的.

Suppose I create it local to the procedure (not global, not in a using). But local to the procedure.

那么肯定可以像其他任何变量一样,在过程完成时自动将其清除,不是吗?

Then surely like any other variables, it will get disposed of automatically when the procedure completes, wouldn't it?

那为什么对我来说手动/显式处理它很重要?

So why is it important for me to dispose it manually/explicitly?

为什么不能让它像其他任何变量一样自动进行垃圾收集?

Why can't I let it garbage collect automatically like any other variable?

当然,它可能比'int'大一点,但它可能仍然很小,而且由于过程结束得如此之快,因此不会在内存中保留很长时间.甚至可能是在使用结束或调用Dispose()之后,过程结束了,因此,如果变量是过程的局部变量,我想将其处置.那么,为什么要麻烦Dispose()/using的显式垃圾回收呢?

Sure it may be perhaps a bit bigger than an 'int' but it might still be quite small and won't be in memory for long since the procedure ends so fast anyway. It may even be that straight after the using is finished or the Dispose() is called, the procedure ends and thus I suppose it'd be disposed, if the variable was local to the procedure. So why bother with the explicit garbage collection of Dispose()/using?

推荐答案

Microsoft .NET类库提供了通过System.Drawing命名空间进行GDI +的托管接口. GDI +是基于C ++的,并产生对非托管对象的引用.因此,重要的是放置System.Drawing命名空间的可抛弃对象,因为垃圾管理器不会自动处置未管理的对象.这些对象可能包含完成此工作的终结器.但是,您无法控制何时执行这些终结器.即将完成的终结器也使堆变得混乱.因此,最好显式地调用Dispose()或通过using语句来调用.

The Microsoft .NET class library provides a managed interface for GDI+ via the System.Drawing namespace. GDI+ is C++-based and yields references to non-managed objects. It is therefore important to dispose the disposable objects of the System.Drawing namespace, because non-manged objects are not disposed automatically by the garbage collector. These objects might contain finalizers that do the job; however, you are not in the control of when these finalizers are executed. Also pending finalizers are cluttering the heap. It is therefore better to call Dispose() explicitly or by the means of a using-statement.

这篇关于为什么要处置一定会很快被处置的物体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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