【问题标题】:If I have a connection in a using statement, will the connection be closed if an exception occurs in the using statement?如果我在 using 语句中有连接,如果在 using 语句中出现异常,是否会关闭连接?
【发布时间】:2014-04-22 22:34:39
【问题描述】:

以下代码没有任何类型的错误处理。

不过我很好奇。就目前而言,在抛出异常时是否会关闭在 using 语句中创建的连接?或者连接是否会因为从未明确关闭而保持打开状态?

public override string ResetToDefault() {
    string result;
    using (var cn = HostFacade.GetDbConnection())
    {
        cn.Open();
        DbProvider.Transaction = cn.BeginTransaction();

        // Do something here that throws an unhandled exception.

        DbProvider.Transaction.Commit();
        cn.Close();
    }
    return result;
}

编辑:HostFacade.GetDbConnection 返回的连接是一个 IDbConnection。假设它被实现为 SqlConnection 对象是安全的。

【问题讨论】:

    标签: c# database exception connection using


    【解决方案1】:

    是的,因为using 语句被编译器扩展为try...finally 块。你的代码是这样的:

    SqlConnection cn = null;
    
    try {
        cn = HostFacade.GetDbConnection();
        cn.Open();
        // .. rest of the code here
    }
    finally {
        if (cn != null)
            cn.Dispose();
    }
    

    Dispose 调用将关闭连接。

    CLR 保证 finally 块将执行.. 除非在非常特殊的情况下(例如调用 FailFastIIRC)。

    【讨论】:

    • Dispose 调用将关闭连接。你确定吗?
    • @Selman22 是的。我是。来自文档:To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block。 Reflector 还通过在SqlConnectionDispose 方法中调用this.Close() 来支持它。
    • 如果没有提供 using 语句,它会保持连接打开吗?换句话说,编译器是否只期望在实现 using 语句时 try...finally 阻塞?
    • 如果它是一个池连接,它并没有真正关闭。如果您查看参考源,您可能会看到对 Close 的调用没有执行任何操作,并且在下面的 DisposeMe 中,检查了 Pooling 选项。但是从这个问题的角度来看,连接是关闭的。
    • 让我们阅读问题,因为它的意思是:Does this leak resources?。答:没有。
    【解决方案2】:

    这取决于您正在运行的特定库的作者对Dispose() 的实现。

    .NET Framework 中内置的库(如您的示例)无疑会清理访问的资源,如 SqlConnection,但您应该先验证文档,然后再进行假设。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多