如何在多个线程之间共享一个mysql连接? [英] How to share a one mysql connection between multiple threads?

查看:144
本文介绍了如何在多个线程之间共享一个mysql连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我使用来自dev.mysql.com的Mysql.Data连接器写入我的mysql数据库,并且我想最大化性能,所以我不想打开许多MySql连接.但是最终,当我尝试使用一个全局静态连接时,像这样:

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

我遇到了System.Threading.SynchronizationLockException.所以我的问题是:使用dev mysql连接器在不同线程之间共享一个连接的正确方法是什么?

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

推荐答案

使用dev mysql连接器在不同线程之间共享一个连接的正确方法是什么?

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.

这篇关于如何在多个线程之间共享一个mysql连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆