在循环中打开和关闭连接的正确方法

Proper way to open and close connection in loop

我有如下代码:

public void Do
{
      using (var myConnection = new SqlConnection(connectionString))
      {
           for (int i = 0; i < 4; i++)
           {
               MyProcess.Execute(myConnection);

           }
           myConnection.Close();
           myConnection.dispose();
      }
}
public class MyProcess
{
     public void Execute(SqlConnection myConnection)
     {
          if (myConnection.State == ConnectionState.Closed)
                myConnection.Open();
          //long running code
     }
}

Execute methods 每次迭代有时需要 5-10 分钟,有时 运行 需要 1-2 分钟。

现在我很困惑,我是否应该为每次迭代打开和关闭连接并且这将是有效的,或者我是否只打开和关闭连接 1 次。

但是打开和关闭连接一次,这将为每次迭代保留资源并消耗资源。

所以我没有得到处理这个问题的正确方法

有人可以给我一些建议吗?

ADO.NET 在后台使用 Connection Pooling。这就是为什么每次打开一个新连接都不成问题。您对 myConnection.Open() 的调用实际上不会每次都打开与数据库的物理连接。

同时检查 。它的作者对连接打开进行了测量测试。我已经向他展示了随后调用 DbConnection.Open() 的时间接近 0.

使用 DbConnection 的最佳方式是打开它的时间最短。如果您的 MyProcess.Execute() 有很多其他 non-DB 相关逻辑需要相当长的时间,您不应该在此执行期间保持打开的连接。

另请查看 Best Practices for Using ADO.NET 文章。它有以下明确的声明:

High performance applications keep connections to the data source in use for a minimal amount of time, as well as take advantage of performance enhancing technology such as connection pooling.

So when does Ado.net removes the connection from connection pool?

This article 提供了一些关于连接池的内部细节:

The connection pooler removes a connection from the pool after it has been idle for approximately 4-8 minutes, or if the pooler detects that the connection with the server has been severed. Note that a severed connection can be detected only after attempting to communicate with the server. If a connection is found that is no longer connected to the server, it is marked as invalid. Invalid connections are removed from the connection pool only when they are closed or reclaimed.

如果需要,本文还提供了一些关于池调整的详细信息。但是,只有当您遇到由池引起的一些性能问题时,您才应该考虑这种手动配置。