c# - 在 C# 中完成方法指南和最佳实践

标签 c# .net coding-style finalize

<分区>

我最近遇到了一个与在 Finalize 方法重载中运行的代码有关的问题。

我主要了解与内存管理/性能相关的问题,但我很感兴趣是否有关于“哪些代码应该/不应该进入 Finalize 方法”的指南?

例如:

  1. 不要在 Finalize 方法中抛出异常。
  2. 代码应该快速执行。
  3. 不引发事件(?)
  4. 等等...

我的案例中的行为是由于引发了导致某些异常的事件而出现的。

所以我的问题是——关于终结方法,我必须遵循哪些准则(甚至可能强制使用某些工具)?

最佳答案

终结只是为了摆脱非托管资源

来自 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/

相关文章:

html - CSS 元素规则

android - 检查方法中的 Android 权限

android - TextView state_pressed/state_focused/state_selected 样式改变

c# - 如何在非唯一列表中存储一对字符串

c# - Task<IList<>> 作为 Func<> 的结果

c# - 如何在表单中呈现列表项?

c# - 使用 Azure Service Fabric 构建微服务的权衡和最佳实践

.net - 在混合模式 C++ 项目中从 CLR 到 SEH 异常获取敏感信息

.net - Windows API根据未使用的变量名称导致不同的结果?

c# - 嵌套循环的更快替代方案?