【问题标题】:Is IDisposeable Called if Un-Handled Exception is Encountered in a Using Statement?如果在 using 语句中遇到未处理的异常,是否会调用 IDisposeable?
【发布时间】:2010-11-24 20:50:35
【问题描述】:

如果我有以下情况,是否仍会在 DisposeableObject 上调用 IDisposeable,或者该对象是否会因为遇到未处理的异常而保持打开状态?

using ( DisposeableObject = new Object() )
{
   throw new Exception("test");
}

【问题讨论】:

标签: c# using-statement


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      在您提供的示例中,将在引发异常之前调用 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
      }
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          当异常冒出时,对象将被释放,因为您将超出范围。

          见:using Statement (C# Reference)

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-10-05
            • 1970-01-01
            • 2016-10-24
            • 1970-01-01
            • 2012-01-08
            • 1970-01-01
            • 1970-01-01
            • 2012-04-15
            相关资源
            最近更新 更多