c# - 带有 using 子句的 SqlConnection - 在连接上调用关闭

标签 c# asp.net .net

当我在如下所示的 using 子句中有一个 SQLConnection 时,我是否需要显式关闭连接?

protected SqlConnection Connection 
{
    get
    {
       if (this.connection == null)
       {
           this.connection = new SqlConnection(this.ConnectionString);
       }
       if (this.connection.State != ConnectionState.Open)
       {
           this.connection.Open();
       }

       return this.connection;
    }
} 

using (SqlConnection connection = this.Connection)
{
    using (SqlCommand cmd = connection.CreateCommand())
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "....";

        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                etc
            }
        }
    }
}

最佳答案

不,你不知道。如果连接已经打开,连接的 Dispose() 方法将调用 Close。

您还应该按照 John Gathogo 的建议更改您的代码,以便在每次需要时创建一个新的连接对象。您的代码将按原样失败,因为您第二次尝试使用该连接时,它已经被处理掉了。

ADO.NET 使用连接池来保留打开的连接池,它提供给任何调用 Open 的人。这意味着只要池中有可用连接,创建和打开新连接就不会花费任何费用。保持连接打开的时间超过必要的时间会降低性能。

关于c# - 带有 using 子句的 SqlConnection - 在连接上调用关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11135061/

相关文章:

.net - Ruby 使用 native 工具包进行跨平台开发的可行性?

c# - 在 Entity Framework 和 Linq to Entities 中使用规范模式和表达式

c# - 从数组 C# 中删除字符串

asp.net - silverlight 不支持 wsHttpBinding

c# - 使用 TimeZoneInfo.GetSystemTimeZones() 时获取 Windows 时区索引;

c# - 自动化从一个文件夹中的多个 CSV 文件导出数据的过程

c# - 将 double 转换为 decimal 还是从 double 构造 "new"decimal 更好?

c# - 测试 HttpResponse.StatusCode 的结果

c# - NUnit 测试适配器显示重复的失败测试

c# - 如何在 .Net Core 1.0 中使用 XPathSelectElement?