【问题标题】:If an Exception happens within a using statement does the object still get disposed?如果在 using 语句中发生异常,该对象是否仍会被释放?
【发布时间】:2012-01-08 17:46:21
【问题描述】:

如果在 using 语句中发生异常,对象是否仍会被释放?

我问的原因是因为我试图决定是在整个代码块周围还是在内部 using 语句中进行尝试。请记住,某些异常会按设计在 catch 块内重新抛出。

using (SPSite spSite = new SPSite(url))
{
   // Get the Web
   using (SPWeb spWeb = spSite.OpenWeb())
   {
       // Exception occurs here
   }
}

【问题讨论】:

    标签: c# exception-handling try-catch using


    【解决方案1】:

    是的,他们会的。

    using(SPWeb spWeb = spSite.OpenWeb())
    {
      // Some Code
    }
    

    等价于

    {
      SPWeb spWeb = spSite.OpenWeb();
      try
      {
    
        // Some Code
      }
      finally
      {
        if (spWeb != null)
        {
           spWeb.Dispose();
        }
      }
    }
    

    编辑

    在回答完这个问题后,我在我的博客中写了一篇关于IDisposable and Using 构造的更深入的帖子。

    【讨论】:

      【解决方案2】:

      是的。 using 语句大致转换为以下构造:

      IDisposable x;
      try
      {
          ...
      }
      finally
      {
          x.Dispose();
      }
      

      【讨论】:

        【解决方案3】:

        是的。这就像将您的代码包装在 try-finally 中(并在 finally 中处理)。

        【讨论】:

          【解决方案4】:

          using 语句导致生成完整且正确的dispose 模式,因此答案是肯定的。

          【讨论】:

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