<分区>
我最近遇到了一个与在 Finalize 方法重载中运行的代码有关的问题。
我主要了解与内存管理/性能相关的问题,但我很感兴趣是否有关于“哪些代码应该/不应该进入 Finalize 方法”的指南?
例如:
- 不要在 Finalize 方法中抛出异常。
- 代码应该快速执行。
- 不引发事件(?)
- 等等...
我的案例中的行为是由于引发了导致某些异常的事件而出现的。
所以我的问题是——关于终结方法,我必须遵循哪些准则(甚至可能强制使用某些工具)?
<分区>
我最近遇到了一个与在 Finalize 方法重载中运行的代码有关的问题。
我主要了解与内存管理/性能相关的问题,但我很感兴趣是否有关于“哪些代码应该/不应该进入 Finalize 方法”的指南?
例如:
我的案例中的行为是由于引发了导致某些异常的事件而出现的。
所以我的问题是——关于终结方法,我必须遵循哪些准则(甚至可能强制使用某些工具)?
最佳答案
终结只是为了摆脱非托管资源
来自 MSDN
If Finalize or an override of Finalize throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process and no active try-finally blocks or finalizers are executed. This behavior ensures process integrity if the finalizer cannot free or destroy resources.
Finalize operations have the following limitations:
The exact time when the finalizer executes during garbage collection is undefined. Resources are not guaranteed to be released at any specific time, unless calling a Close method or a Dispose method.
The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other. That is, if Object A has a reference to Object B and both have finalizers, Object B might have already finalized when the finalizer of Object A starts.
The thread on which the finalizer is run is unspecified
关于c# - 在 C# 中完成方法指南和最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10571927/