简体   繁体   English

在.NET应用程序中关闭MySQL连接是否很重要? (确切地说,C#)

[英]Is closing a MySQL connection important in a .NET application ? (To be exact, C#)

Some first things that people learned in their early use of MySQL that closing connection right after its usage is important, but why is this so important? 人们在早期使用MySQL时所学到的一些事情,即在使用后立即关闭连接很重要,但为什么这么重要呢? Well, if we do it on a website it can save some server resource (as described here ) But why we should do that on a .NET desktop application? 那么,如果我们做一个网站,它可以节省一些服务器资源(如描述在这里 ),但为什么我们应该做的是在.NET桌面应用程序? Does it share the same issues with web application? 它是否与Web应用程序共享相同的问题? Or are there others? 或者还有其他人吗?

If you use connection pooling you won't close the physical connection by calling con.Close , you just tell the pool that this connection can be used. 如果使用连接池,则不会通过调用con.Close关闭物理连接,只需告诉池可以使用此连接。 If you call database stuff in a loop you'll get exceptions like "too many open connections" quickly if you don't 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 of the possible exceptions: 一个可能的例外:

Timeout expired. 超时已过期。 The timeout period elapsed prior to obtaining a connection from the pool. 从池中获取连接之前经过的超时时间。 This may have occurred because all pooled connections were in use and max pool size was reached. 这可能是因为所有池连接都在使用中并且达到了最大池大小。

By the way, the same is true for a MySqlConnection . 顺便说一句, MySqlConnection也是如此。

This is the correct way, use the using statement on all types implementing IDsiposable : 这是正确的方法,在实现IDsiposable所有类型上使用using语句:

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

Yes I think it is important to close out your connection rather than leaving it open or allowing the garbage collector to eventually handle it. 是的我认为关闭你的连接而不是让它打开或允许垃圾收集器最终处理它是很重要的。 There are a couple of reason why you should do this and below that I'll describe the best method for how 有几个原因,为什么你应该做这做那下面我将介绍如何最好的方法

WHY: 为什么:

So you've opened a connection to the database and sent some data back and forth along this pipeline and now have the results you were looking for. 因此,您已打开与数据库的连接,并沿此管道来回发送一些数据,现在可以获得您正在寻找的结果。 Ideally at this point you do something else with the data and the end results of your application is achieved. 理想情况下,此时您可以使用数据执行其他操作,并实现应用程序的最终结果。

Once you have the data from the database you don't need it anymore, its part in this is done so leaving the connection open does nothing but hold up memory and increase the number of connections the database and your application has to keep track of and possibly pushing you closer to your maximum number of connections limit. 一旦你从数据库中的数据,你不需要它了,它在这部分做了离开连接开放不只是撑起内存和增加连接数据库的数量和你的应用程序来跟踪可能会让你更接近你的最大连接数限制。

"But wait! I have to make a lot of database calls in rapid succession!" “但是等等!我必须快速连续进行大量的数据库调用!”

Okay no problem, open the connection run your calls and then close it out again. 好的没问题,打开连接运行你的电话,然后再将其关闭。 Opening a connection to a database in a "modern" application isn't going to cost you a significant amount of computing power/time, while explicitly closing out a connection does nothing but help (frees up memory, lowers your number of current connections). 在“现代”应用程序中打开与数据库的连接不会花费您大量的计算能力/时间,而明确关闭连接只会提供帮助(释放内存,降低当前连接数) 。

So that is the why, here is the how 这就是为什么,这就是方法

HOW: 怎么样:

So depending on how you are connecting to your MySQL database you a probably using an IDisposible object to help manage the connection. 因此,根据您连接MySQL数据库的方式,您可能使用IDisposible对象来帮助管理连接。 Here is what MSDN has to say on using an IDisposable: 以下是MSDN对使用IDisposable的看法:

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. 通常,当您使用IDisposable对象时,您应该在using语句中声明并实例化它。 The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. using语句以正确的方式调用对象上的Dispose方法,并且(如前所示使用它时)一旦调用Dispose,它也会导致对象本身超出范围。 Within the using block, the object is read-only and cannot be modified or reassigned. 在using块中,该对象是只读的,不能修改或重新分配。

Here is my personal take on the subject: 以下是我个人对此主题的看法:

  1. Using a using block helps to keep your code cleaner (readability) 使用using块有助于保持代码清洁(可读性)
  2. Using a using block helps to keep your code clear (memory wise), it will "automagically" clean up unused items 使用using块有助于保持代码清晰(以内存方式),它将“自动”清理未使用的项目
  3. With a using block it helps to prevent using a previous connection from being used accidentally as it will automatically close out the connection when you are done with it. 使用using块有助于防止意外使用以前的连接,因为它会在您完成连接时自动关闭连接。

In short, I think it is important to close connections properly, preferably with a con.close() type statement method in combination with a using block 简而言之,我认为正确关闭连接很重要,最好使用con.close()类型语句方法结合using

As pointed out in the comments this is also a very good question/answer similar to yours: Why always close Database connection? 正如评论中指出的那样,这也是一个非常好的问题/答案,类似于你的: 为什么总是关闭数据库连接?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM