Is closing a MySQL connection important in a .NET application? (More specifically, C #)

Some of the first things people learned when using MySQL early that closing a connection right after using it is important, but why is it so important? Well, if we do this on a website, it can save some server resource (as described here ). But why should we do this on a .NET desktop application? Does he have the same problems with a web application? Or are there others?

+4
source share
2 answers

If you use a connection pool, you do not close the physical connection by calling con.Close, just tell the pool that this connection can be used. If you invoke database material in a loop, you will quickly get exceptions, such as "too many open connections" if you did not close them.

Check this:

for (int i = 0; i < 1000; i++)
{
    var con = new SqlConnection(Properties.Settings.Default.ConnectionString);
    con.Open();
    var cmd = new SqlCommand("Select 1", con);
    var rd = cmd.ExecuteReader();
    while (rd.Read())
        Console.WriteLine("{0}) {1}", i, rd.GetInt32(0));
}

One possible exception:

Timed out. Waiting period before receiving connection to the pool. Perhaps this happened because all pooled connections were used and the maximum pool size was reached.

By the way, the same is true for a MySqlConnection.

This is the correct way, use the operator usingfor all types that implement IDsiposable:

using (var con = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
    con.Open();
    for (int i = 0; i < 1000; i++)
    {
        using(var cmd = new SqlCommand("Select 1", con))
        using (var rd = cmd.ExecuteReader())
            while (rd.Read())
                Console.WriteLine("{0}) {1}", i, rd.GetInt32(0));
    }
}// no need to close it with the using statement, will be done in connection.Dispose
+6
source

, , , . , , ,

:

, , , . - , .

, , , , , , , , .

" , !"

, , , . "" /, ( , ).

, ,

:

, , MySQL, , , IDisposible . MSDN IDisposable:

, IDisposable, using. using ( ), , Dispose . .

:

  • using ()
  • using ( ), "" .
  • using , , .

, , , con.close() using

, /, : ?

+3

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


All Articles