我有这门课:
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) 我会用 Try
和 Cache
包装它 - 我将永远
知道有错误
3) 我应该在这里做什么
?
编辑
MSDN它的模式基于 “如果我**忘记**调用 Dispose 方法 - 所以 GC 最终会执行它......最好以后再做......”
。所以我的问题是特别是关于 Finilize(析构函数)中的异常
最佳答案
这实际上取决于.NET框架
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/