简体   繁体   English

应用无法正确关闭MySql连接

[英]App not closing MySql connection properly

I'm having a serious issue with my app. 我的应用程序出现严重问题。 It builds a lot of MySql connections and then it's causing a crash. 它建立了许多MySql连接,然后导致崩溃。

I build every method like that: 我建立了每个这样的方法:

MySqlConnection connect = new MySqlConnection(
        local_connection_string
        ); //this is global variable.

    protected void sample()
    {
        try
        {
            connect.Open();
            MySqlCommand query = new MySqlCommand(
                "here some mysql command"
                , connect);
            query.ExecuteNonQuery();
        }
        catch
        {

        }
        finally
        {
            connect.Dispose();
            connect.Close();
        }
    }

For some reason it's not closing any of these connections and when I keep refreshing it builds connections on the server, once limit is hit app is crashing. 由于某种原因,它没有关闭任何这些连接,当我不断刷新时,它会在服务器上建立连接,一旦达到限制,应用就会崩溃。 All connections are closed when app is shut down. 应用关闭时,所有连接均关闭。

try this: 尝试这个:

using(MySqlConnection conn = new MySqlConnetion(local_connection_string)
{
    conn.open();
    MySqlCommand query = new MySqlCommand(
                "here some mysql command"
                , connect);
            query.ExecuteNonQuery();

}

using(resource){}: right way for IDisposable resource usage probably need to add: Application.ApplicationExit event with MySqlConnection.ClearAllPools() using(resource){}:使用IDisposable资源的正确方法可能需要添加:具有MySqlConnection.ClearAllPools()的Application.ApplicationExit事件

To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. 为了确保始终关闭连接,请在using块内部打开连接,如以下代码片段所示。 Doing so ensures that the connection is automatically closed when the code exits the block. 这样做可确保在代码退出块时自动关闭连接。

using (MySqlConnection connection = new MySqlConnection(connectionString))
{
    connection.Open();
    // Do work here; connection closed on following line.
}

MySQL counter part uses Connection pooling and does not close when you call close instead it puts it in the connection pool! MySQL计数器部分使用连接池,并且在您调用close时不会关闭,而是将其放入连接池中!

Make sure you First Close then Dispose the Reader, Command, and Connection object! 确保先关闭然后处置读取器,命令和连接对象!

You can use ConnectionString Parameter "Pooling=false" or the static methods MySqlConnection.ClearPool(connection) and MySqlConnection.ClearAllPools() 您可以使用ConnectionString参数"Pooling=false"或静态方法MySqlConnection.ClearPool(connection)MySqlConnection.ClearAllPools()

and Using keyword is the right way to go with this kind of Scenario. Using关键字是解决这种情况的正确方法。

Just close first the connection , before calling the dispose... 只需先关闭连接,然后再调用处置...

        finally
        {
            connect.Close();
            connect.Dispose();
        }

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

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