如果在Using语句中遇到未处理的异常,是否会调用IDisposeable?

发布于 2024-10-04 10:39:32 字数 188 浏览 6 评论 0原文

如果我有以下情况,是否仍会在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

说谎友 2024-10-11 10:39:32

using 就像将代码包装在 try...finally 中并在finally中进行处理,所以是的,应该调用它。

A using is like wrapping your code in a try...finally and disposing in the finally, so yes, it should be called.

饮湿 2024-10-11 10:39:32

using 扩展为 try..finally 块,所以是的,它将调用 Dispose。

using expands to a try..finally block, so yes, it will call Dispose.

呆° 2024-10-11 10:39:32

在您提供的示例中,将在引发异常之前调用 Dispose。

确保调用 dispose 的正常代码看起来像

var connection= new SqlConnection(connectionString);
try
{
  // do something with the connection here
}
finally
{
  connection.Dispose();
}

usings 语句,无需编写如此繁琐的语句。

using(var connection = new SqlConnection(connectionString))
{
  // do something with the connection here
}

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

var connection= new SqlConnection(connectionString);
try
{
  // do something with the connection here
}
finally
{
  connection.Dispose();
}

The usings statement replaces the need to write such a cumbersome statement.

using(var connection = new SqlConnection(connectionString))
{
  // do something with the connection here
}
恏ㄋ傷疤忘ㄋ疼 2024-10-11 10:39:32

根据 MSDN,。当控制离开 using 语句的范围时,预计它会被释放。

According to MSDN, yes. When control leaves the scope of the using statement, expect it to be disposed.

沉睡月亮 2024-10-11 10:39:32

当异常出现时,该对象将被处理,因为您将超出范围。

请参阅:using 语句(C# 参考)

using 语句可确保即使在调用对象方法时发生异常,也会调用 Dispose。您可以通过将对象放入 try 块中,然后在 finally 块中调用 Dispose 来实现相同的结果;事实上,这就是编译器翻译 using 语句的方式。

The object will be disposed as you will come out of scope when the exception bubbles up.

See: using Statement (C# Reference)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文