【问题标题】:Do I need to manually close a .NET SqlConnection, if it throws an exception inside a `using` statement? [duplicate]如果 .NET SqlConnection 在 `using` 语句中引发异常,我是否需要手动关闭它? [复制]
【发布时间】:2015-08-24 20:38:19
【问题描述】:

如果SqlConnectionusing 语句内执行期间抛出异常,我是否需要手动关闭finally 中的连接?或者using 语句的范围会为我调用Dispose 方法(在SqlConnection 上)...因此会为我(自动)执行.Close(); 方法?

例如:

using (var sqlConnection = new SqlConnection(_connectionString)
{
   sqlConnection.Open();

   throw new Exception("boom!");
}

using (var sqlConnection = new SqlConnection(_connectionString)
{
    try
    {
        sqlConnection.Open();

        throw new Exception("boom!");
    }
    finally
    {
        sqlConection.Close();
    }
}

此外,是否将其包装在 TransactionScope + 中会引发异常,影响我应该如何 .Close()using 范围自动为我执行此操作。

【问题讨论】:

    标签: c# .net ado.net using sqlconnection


    【解决方案1】:

    不,如果它在using 内,它仍然被释放

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

    来源:MSDN.

    【讨论】:

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