简体   繁体   中英

C# Emulator 'To Many Connections'

I have recently been receiving a mysql to many connectiions error, ive used sql queries such as the one below

SET GLOBAL max_conmnections = 8000; and ive also higherd the mysql.pool.max to 8000 and when my emulator is in the debugger, it crashes on this void

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

     return new SqlDatabaseClient(Id, Connection);
}

the line thats highlighted that has caused it to crash was connection.open(); it happens when i receive 10-12 online connections, the emulator was running for 7-8 hours in the debugger!

What you can try is to close and dispose the connection and commands after used by the C# using statement:

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;
}

I would suggest rewrite into something like:

  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
    });
  }

I think you can add codes like: SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); then, after closing SqlDataReader's instance, the Connection object will also be closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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