C# 如何使用语句转换为 Try-Finally

How C# Using Statement Translates to Try-Finally

我正在努力解决这个问题。根据 this page 关于 Using 的陈述:

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

但是在 this page 关于 Try-Finally 块它指出:

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.

那么如果 Using 语句转换为不保证调用 finally 语句的 Try-Finally 语句,如何保证在发生异常时调用 Dispose 方法?

它确实表现得像 try/finally - 所以如果应用程序终止,资源可能不会被释放......这通常没问题,因为通常释放是为了释放进程持有的资源...... . 并且 OS 无论如何都会在进程死亡时整理它们。 (这并不是说 Dispose 方法 不会 被调用...它与普通的 try/finally 相同。 )

显然,如果你在文件系统上有一个 "lock file" 或类似的东西,那将是一个问题 - 但你在面对停电等情况时也会遇到同样的问题。

存在程序无法恢复的异常,在这种情况下finally 块将不会执行。例如堆栈溢出异常或内存不足异常。

如果异常展开仅以导致程序崩溃的未处理异常结束,则 finally 块不会 运行 因为执行停止。

tl;博士 最后块只有 运行 成功或处理异常。