【问题标题】:C# Emulator 'To Many Connections'C# 模拟器'到多个连接'
【发布时间】:2013-08-19 08:25:16
【问题描述】:

我最近收到一个 mysql to many connectiions 错误,我使用了如下的 sql 查询

SET GLOBAL max_conmnections = 8000; 和我还提高了mysql.pool.max to 8000,当我的模拟器在调试器中时,它在这个 void 上崩溃

private static SqlDatabaseClient CreateClient(int Id)
{
     MySqlConnection Connection = new MySqlConnection(GenerateConnectionString());
     Connection.Open();

     return new SqlDatabaseClient(Id, Connection);
}

导致它崩溃的突出显示的行是connection.open(); 它发生在我收到 10-12 个在线连接时,模拟器在调试器中运行了 7-8 小时!

【问题讨论】:

    标签: c# mysql mysqlconnection


    【解决方案1】:

    你可以尝试的是关闭和处理C#using语句使用后的连接和命令:

    private static SqlDatabaseClient CreateClient(int Id)
    {
        Int32 returnId = 0;
    
        try
        {
          using(MySqlConnection connection = new MySqlConnection(GenerateConnectionString()))
          {
            connection.Open();
    
            if(connection.State == ConnectionState.Open)
            {
               returnId = Id;
            }
    
          }
        }
        catch(Exception exception)
        {
           Console.Write(ex.Message);
        }
        finally
        {
            if(connection.State == ConnectionState.Open)
            {
               connection.Close();
    
            }
        }
    
        return returnId;
    }
    

    【讨论】:

    • 你的意思是在sqldatabaseclient里面加上那个?是我提出的,还是在上面添加?
    • 我更新了答案。如果它以前工作但由于没有处理连接而被炸毁,那么上述可能会解决您的问题
    • 我在问我把这段代码放在哪里?我是 C# 的初学者,我不确定你想把这段代码放在哪里?在它上面?
    • 我已经尝试使用您发布的代码,较长的代码,它出错了,Connetion.State 行出错,returnId 错误编辑说名称“连接”在当前上下文中不存在
    【解决方案2】:

    我建议改写成这样的:

      private static void ExecuteInClientContext(int Id, Action<SqlDatabaseClient> callback) {
        if (callback == null) {
          throw new ArgumentNullException("callback");
        }
    
        using(MySqlConnection Connection = new MySqlConnection(GenerateConnectionString())) {
          Connection.Open();
          callback.Invoke(new SqlDatabaseClient(Id, Connection));
        }
      }
    
      static void Foo() {
        ExecuteInClientContext(1, (context) => {
          // whatever
        });
      }
    

    【讨论】:

    • 我是否用我的整个公共静态 sq;databaaseclient 替换此代码?我需要在 //whatever 上编写任何代码吗
    【解决方案3】:

    我认为您可以添加如下代码: SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); 那么,在关闭SqlDataReader的实例后,Connection对象也会被关闭。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      相关资源
      最近更新 更多