是.NET终结总是执行? [英] Are .net finalizers always executed?

查看:128
本文介绍了是.NET终结总是执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否终结保证在.NET在某些时候(备用电源中断等)的执行?我知道它是如何工作的GC,这是完全的时候,他们会遇到不确定的。

Are finalizers guaranteed to be executed in .NET at some point (spare power outages and the like)? I know how GC works and that it is nondeterministic when exactly they'll run.

(搜索没有显示很好的答案,所以我将这个问题与不那么容易发现实际的答案合并了很高的期望。除此之外,我已经知道了回答和我将在几天后的情况下,没有人提到它添加。)

推荐答案

终结实际上可能的永远的执行,为的Raymond Chen解释。很有趣,这个问题是在他的年度CLR周问,仅仅两天后,他解释道:)

Finalizers may actually be never executed, as Raymond Chen explains. Kind of funny that this question is asked during his annual CLR week, just two days after he explained it :)

对于懒惰的,在(或者更确切地说,一个)的结论是:

For the lazy ones, the (or rather, one) conclusion is:

一个正确编写的程序不能假设的终结将永远运行。

A correctly-written program cannot assume that finalizers will ever run.

如果你想知道你是否能依靠终结,这已经是一切你必须知道:不要依赖于终结

If you are wondering whether you can rely on finalizers, this is already everything you have to know: Don't rely on finalizers.

由于雷蒙德陈还指出,在链接的文章:

As Raymond Chen also states in the linked article:

终结是一个安全网,而不是资源回收的主要手段。

Finalizers are a safety net, not a primary means for resource reclamation.

如果您正在寻找如何释放资源,看看在一次性模式。

If you're looking for how to release resources, have a look at the Disposable pattern.

一个终结器可能无法运行,例如,如果:

A finalizer may not run, for example, if:

  • 在另一个终结引发异常。
  • 在另一个终结的时间超过2秒。
  • 所有终结在一起时间超过40秒。
  • 在一个AppDomain崩溃或卸载(虽然你可以用一个关键的终结(CriticalFinalizerObject,SafeHandle的或类似的东西避开这一点)
  • 在没有垃圾回收时
  • 在该进程崩溃

(注:时间值可能会随着时间而改变,但却千真万确的一些很久以前。)

(Note: The time values may have changed over time, but were certainly true some time ago.)

我想有很多更多的事情,可能会导致终结永远不会运行。底线是,比陈天桥报价等,也终结是的一个安全网,减少错误的影响,因为例如资源被释放的的某个时候的,这比的永远的,如果你忘了明确地做到这一点。

I guess there are a lot more things that can cause finalizers to never run. The bottom line is, other than the quote from Mr. Chen, that finalizers are a safety net that decrease the impact of bugs, because for example resources are released sometime, which is better than never, if you forget to do it explicity.

这篇关于是.NET终结总是执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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