问题描述
终结器是否可以保证在某些时候在 .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.
(搜索没有显示好的答案,所以我添加这个问题是为了与不太容易发现的实际答案合并.除此之外,我已经知道回答并在几天后添加它,以防没有人提到它.)
推荐答案
Finalizers 实际上可能永远被执行,如 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.
正如 Raymond Chen 在链接文章中所说:
As Raymond Chen also states in the linked article:
终结器是一个安全网,而不是资源回收的主要手段.
Finalizers are a safety net, not a primary means for resource reclamation.
如果您正在寻找如何释放资源,请查看 Disposable 模式.
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 终结器是否总是执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!