gpt4 book ai didi

c# - 为什么即使使用 using 语句也不调用 Dispose?

转载 作者:行者123 更新时间:2023-11-30 19:53:40 25 4
gpt4 key购买 nike

我有这个控制台应用程序(.NET Framework 4.5.2):

class Program
{
static void Main(string[] args)
{
using (var result = new Result())
{
result.Test();
}
}
}

public class Result : IDisposable
{
public void Test()
{
int a = 1;
int b = 1 / (a - 1);
}

public void Dispose()
{
Console.WriteLine("Dispose");
}
}

为什么Dispose 方法没有被调用?在 DivideByZero 异常之后,Dispose 中没有命中断点,并且控制台上没有输出(因为应用程序退出)。

最佳答案

根据 MS 文档:try-finally (C# Reference)

Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered. That, in turn, is dependent on how your computer is set up.

由于您没有捕获 DivideByZero 异常并让它未被处理,因此在您的 机器和设置上它必须在任何其他代码行之前关闭应用程序运行,因此不运行 finally block 。

正如@Evk 在下面的评论中指出的那样,如果我在没有附加调试器的情况下运行它,它会正确展开异常并执行 finally block 。每天学习新东西。

根据 Eric Lippert's answer to Finally Block Not Running?

Think about how awful that situation is: something unexpected has happened that no one ever wrote code to handle. Is the right thing to do in that situation to run even more code, that was probably also not built to handle this situation? Possibly not. Often the right thing to do here is to not attempt to run the finally blocks because doing so will make a bad situation even worse. You already know the process is going down; put it out of its misery immediately.

In a scenario where an unhandled exception is going to take down the process, anything can happen. It is implementation-defined what happens in this case: whether the error is reported to Windows error reporting, whether a debugger starts up, and so on. The CLR is perfectly within its rights to attempt to run finally blocks, and is also perfectly within its rights to fail fast. In this scenario all bets are off; different implementations can choose to do different things.

关于c# - 为什么即使使用 using 语句也不调用 Dispose?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47153806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com