使用 (var connection = new SqlConnection("ConnectionString")) 是否仍然关闭/处理错误连接?

Dra*_*lut 1 .net c# t-sql sql-server sqlconnection

我有以下代码

try
{
    using (var connection = new SqlConnection(Utils.ConnectionString))
    {
        connection.Open();

        using (var cmd = new SqlCommand("StoredProcedure", connection))
        {                            
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            var sqlParam = new SqlParameter("id_document", idDocument);
            cmd.Parameters.Add(sqlParam);

            int result = cmd.ExecuteNonQuery();
            if (result != -1)
                return "something";

            //do something here

            return "something else";
        }
    }

    //do something
}
catch (SqlException ex)
{
    return "something AKA didn't work";
}
Run Code Online (Sandbox Code Playgroud)

问题是:var connection如果using括号 ( { })之间发生意外错误,是否仍然关闭?

问题是我对存储过程的大部分调用都是这样进行的,最近我收到了这个错误:

System.InvalidOperationException:超时已过期。在从池中获取连接之前超时时间已过。这可能是因为所有池连接都在使用中并且达到了最大池大小。

我访问数据库的另一种方式是通过 nHibernate。

CD.*_*D.. 5

using 语句(C# 参考)

using 语句确保 Dispose 被调用,即使在您调用对象的方法时发生异常。您可以通过将对象放在 try 块中,然后在 finally 块中调用 Dispose 来获得相同的结果;事实上,这就是编译器如何翻译 using 语句。前面的代码示例在编译时扩展为以下代码(注意额外的大括号以创建对象的有限范围):