1

In my application i'm using Mysql.Data connector from dev.mysql.com to write into my mysql database, and i want to maximize performance, so i don't want to open many MySql connections. But eventually when i tried to use one global static connection like so:

MySqlConnection connect = new MySqlConnection(connectionString);

connect.Open();
StaticData.mysqlConnect = connect;

...


// in my threads
lock (StaticData.mysqlConnect)
{
  foreach (Object param in records)
  {
      using (MySqlCommand command = conn.CreateCommand())
      {
        command.CommandText = "some request";
        //...                   
        command.ExecuteNonQuery();  
      }
  }
}

I got System.Threading.SynchronizationLockException. So my question is: whats the proper way to share one connection between different threads using dev mysql connector?

4

1 回答 1

4

whats the proper way to share one connection between different threads using dev mysql connector?

Don't. Have a different connection on each thread.

The connections should be pooled, so when you open up a new connection it's not going to actually open up a new connection, it's just going to grab an open connection from the pool.

Because of that there's no reason to have such long lived connections shared between threads. Just create a new connection for the scope of each logical transaction and let the connection pooling take care of the rest.

于 2013-10-18T20:41:03.283 回答