C# Using 语句如何转换为 Try-Finally [英] How C# Using Statement Translates to Try-Finally

查看:37
本文介绍了C# Using 语句如何转换为 Try-Finally的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力解决这个问题.根据本页上的Using语句:

I'm trying to wrap my head around this. According to this page on Using statements:

using 语句确保即使在调用对象方法时发生异常,也会调用 Dispose.您可以通过将对象放在 try 块中,然后在 finally 块中调用 Dispose 来获得相同的结果;实际上,编译器就是这样翻译 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.

但是在这个页面上关于Try-Finally阻止了它状态:

But on this page about Try-Finally blocks it states:

在已处理的异常中,保证运行相关的 finally 块.但是,如果异常未处理,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 语句转换为不能保证调用的Try-Finally,那么如何保证在发生异常时调用Dispose 方法finally 语句?

So how can a Using statement be guaranteed to call the Dispose method in the event of an exception if it translates to a Try-Finally that is not guaranteed to call the finally statement?

推荐答案

它确实表现得像一个 try/finally - 所以如果应用程序终止,资源可能不会被释放......这通常没问题,因为通常会被释放用于释放进程持有的资源......操作系统会在进程死亡时整理这些资源.(这并不是说 Dispose 方法不会被调用......它和普通的 try/ 一样最后.)

It really does behave like a try/finally - so if the application terminates, the resource may not be disposed... and that's usually okay, because normally disposal is for releasing resources held by the process... and the OS will tidy those up anyway on process death. (That's not to say the Dispose method won't be called... it's just the same as with a normal try/finally.)

显然,如果您在文件系统上有一个锁定文件"或类似的东西,那将是一个问题 - 但在停电等情况下您也会遇到同样的问题.

Obviously if you've got a "lock file" on the file system or something like that, that would be a problem - but you'd have the same problem in the face of a power cut etc.

这篇关于C# Using 语句如何转换为 Try-Finally的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆