Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 带有using子句的SqlConnection-在连接上调用close_C#_Asp.net_.net - Fatal编程技术网

C# 带有using子句的SqlConnection-在连接上调用close

C# 带有using子句的SqlConnection-在连接上调用close,c#,asp.net,.net,C#,Asp.net,.net,如下图所示,当我在using子句中有一个SQLConnection时,我是否需要显式关闭连接 protected SqlConnection Connection { get { if (this.connection == null) { this.connection = new SqlConnection(this.ConnectionString); } if (this.connection

如下图所示,当我在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的人。这意味着只要池中有可用的连接,创建和打开新连接就不需要任何费用。将连接保持在打开状态的时间过长会降低性能。

您可以轻松地将代码更改为以下内容并实现所需:

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

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

运行时将负责关闭连接并为您处置资源

使用的
块将始终调用
处置
,这将关闭连接


但是,您正在保留连接对象并打算重新使用它,一旦它被释放,这是不可能的。你不应该保留连接对象,你应该扔掉它,在需要的时候创建一个新的。数据库的实际连接是池连接,因此当您创建新的连接对象时,它将重用池中的一个连接。处置连接对象时,实际连接将返回池。

Yes“当使用块结束时,它将自动调用connection.dispose()。dispose显式调用connection.Close(),以及其他内容”如“请不要重用连接对象”,一旦对其调用dispose,它将失败