如果在Using语句中遇到未处理的异常,是否会调用IDisposeable?
如果我有以下情况,是否仍会在 DisposeableObject 上调用 IDisposeable,或者该对象是否会因为遇到未处理的异常而保持打开状态?
using ( DisposeableObject = new Object() )
{
throw new Exception("test");
}
If I have the following, will IDisposeable still be called on DisposeableObject, or will the object remain opened because an un-handled exception is encountered?
using ( DisposeableObject = new Object() )
{
throw new Exception("test");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
using
就像将代码包装在try...finally
中并在finally中进行处理,所以是的,应该调用它。A
using
is like wrapping your code in atry...finally
and disposing in the finally, so yes, it should be called.using 扩展为 try..finally 块,所以是的,它将调用 Dispose。
using expands to a try..finally block, so yes, it will call Dispose.
在您提供的示例中,将在引发异常之前调用 Dispose。
确保调用 dispose 的正常代码看起来像
usings 语句,无需编写如此繁琐的语句。
In the example you provided Dispose will be called before the exception is thrown.
The normal code for ensuring that dispose gets called looks like
The usings statement replaces the need to write such a cumbersome statement.
根据 MSDN,是。当控制离开
using
语句的范围时,预计它会被释放。According to MSDN, yes. When control leaves the scope of the
using
statement, expect it to be disposed.当异常出现时,该对象将被处理,因为您将超出范围。
请参阅:using 语句(C# 参考)
The object will be disposed as you will come out of scope when the exception bubbles up.
See: using Statement (C# Reference)