The correct way to open and close a connection in a loop

I have a code as below:

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 sometimes it takes 5-10 minutes, sometimes it takes 1-2 minutes for each iteration.

Now I am confused by the fact that I will open and close the connection for each iteration, and it will be effective or I only open and close the connection only 1 time.

But when opening and closing the connection once it will contain a resource for each iteration and will consume the resource.

So, I don’t understand how to handle this properly

Can someone please give me some advice on this?

+4
source share
1 answer

ADO.NET Connection Pooling . . myConnection.Open() .

. . , DbConnection.Open() 0.

DbConnection . MyProcess.Execute() , , , .

ADO.NET. :

, .

, Ado.net ?

:

, 4-8 , , . , . , , . , .

, . ​​ , , .

+8

Source: https://habr.com/ru/post/1695341/


All Articles