c# - 如果 .NET SqlConnection 在 `using` 语句内引发异常,我是否需要手动关闭它?

标签 c# .net ado.net using sqlconnection

如果 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范围自动为我执行此操作。

最佳答案

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

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.

Source : MSDN.

关于c# - 如果 .NET SqlConnection 在 `using` 语句内引发异常,我是否需要手动关闭它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32181948/

相关文章:

c# - 如何使用 Metro 应用程序 win8 在 xaml 中添加用户控件?

c# - 翻译实现

c# - 如何在 .net DLL 中编辑 C# 代码

c# - 获取有序字典中的最后一项?

c# - 如果我在单独的文件中使用连接类,ADO.NET 如何添加参数?

c# - 通过字符串和 varchar(max) 之间的比较来更新查询

c# - 是否有一种设计模式可以帮助比较大量数据?

c# - 为什么我的静态方法隐藏了我的实例方法?

c# - WCF 消息凭证实现细节

使用派生接口(interface)的 C# 接口(interface)实现