C#MySQL连接 - MultiThreading - 无法连接

时间:2018-01-21 18:07:53

标签: c# mysql multithreading asynchronous connection

首先一切都运行良好。我正在运行一个程序,每个程序包含100个线程,正在建立数据库连接一段时间后,我收到以下错误消息:

  

“无法连接到任何指定的mysql主机”(内部异常:   连接超时)

MySQL服务器在Windows机器上运行(Win Server 2012)。

我已将mySql连接限制设置为10k,但问题仍然存在

using (MySqlConnection mConnection = new MySqlConnection(connectionString))
{
        mConnection.Open();

        using (MySqlCommand myCmd = new MySqlCommand("XXX"))
        {
            myCmd.CommandType = CommandType.Text;

            // DO STUFF HERE
            myCmd.Connection.Dispose();
        }

        mConnection.Close();
        mConnection.Dispose();
}

1 个答案:

答案 0 :(得分:0)

也许这会解决您的问题:

 using (MySqlConnection mConnection = new MySqlConnection(connectionString))
 {
     using (MySqlCommand myCmd = mConnection.CreateCommand())
     {
         mConnection.Open();
         myCmd.CommandTimeout = 60;
         myCmd.CommandType = CommandType.Text;
         myCmd.CommandText = "XXX";

         using (var reader = cmd.ExecuteReader())
         {
             while (reader.Read())
             {
                 // DO STUFF HERE
             }
         }
     }
 }

您可以根据需要设置超时值(请注意,因为超时是以秒为单位而不是毫秒)。

如果您使用的是.Close(),则无需使用.Dispose()using () { ... }

编辑:根据以下评论更新答案。