c# - 析构函数 (c#) 中的异常?

标签 c# exception .net-4.0 garbage-collection destructor

我有这门课:

public class TempFileRef
    {
        public readonly string FilePath;

        public TempFileRef(string filePath)
        {
            FilePath = filePath;
        }

        ~TempFileRef()
        {
            File.Delete(FilePath);    //<== what happens if exception ?
        }
    }

问题:

如果析构函数中出现异常会怎样?

1) 它会破坏 F-Queue 中的其他终结吗?

2) 我会用 TryCache 包装它 - 我将永远知道有错误

3) 我应该在这里做什么

编辑

MSDN它的模式基于 “如果我**忘记**调用 Dispose 方法 - 所以 GC 最终会执行它......最好以后再做......”。所以我的问题是特别是关于 Finilize(析构函数)中的异常

最佳答案

这实际上取决于.NET框架

例如 .NET 2.NET 4 ,你的申请将被终止

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.

对比 .NET 1 ,只有那个终结器会被终止,你的应用程序会继续运行:

If Finalize or an override of Finalize throws an exception, the runtime ignores the exception, terminates that Finalize method, and continues the finalization process.

您实际要做的是实现 IDisposable 模式,因此不要将这项工作留给 finilazer,而是在名为 Dispose 的程序中完成。

关于c# - 析构函数 (c#) 中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9903001/

相关文章:

wpf - 验证错误模板装饰器被切入 ScrollViewer 中

c# - LINQ 多重排序依据

c# - 哪种算法更适合在数据库中隐藏重要字符串? (该字符串不是密码)

c# - 当 .NET 线程抛出异常时会发生什么?

Ruby 异常或错误?

.net - 如何处理 System.Drawing 形状上的点击事件

c# - 使用什么来安排 .NET 应用程序每天运行?

c# - CaSTLe ActiveRecord 的 ActiveRecordMediator<> 支持 LINQ 吗?

c# - IIS 和 Windows 身份验证上的 NancyFx

java - 在 Spring webflow 中捕获 "dead" session