[英]Testing C# MySQL connection pooling fails with Exception: Connection must be valid and open
I am trying to use connection pooling on MySQL's .net connector 6.6.4.0 to serve multiple threads using the code below: 我正在尝试使用以下代码在MySQL的.net连接器6.6.4.0上使用连接池来服务多个线程:
static public uint uNonQuery(string query)
{
using (Connection = new MySqlConnection(ConnectionString))
{
if (Connection.State == ConnectionState.Open)
{
Console.WriteLine("Its open..>!!!!");
}
Connection.Open();
MySqlCommand cmd = new MySqlCommand(query, Connection);
cmd.ExecuteNonQuery();
MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT LAST_INSERT_ID() AS 'identity'", Connection);
DataTable dt = new DataTable();
adapter.Fill(dt);
uint ret = 0;
if (dt.Rows.Count > 0)
{
try
{
ret = Convert.ToUInt32(dt.Rows[0]["identity"]);
}
catch
{
ret = 0;
}
}
else
ret = 0;
Connection.Close();
return ret;
}
}
My connection string is 我的连接字符串是
"server = 127.0.0.1; user id = ****; password = ****; database = testdb; pooling=true; maximumpoolsize=500;"
And the thread for testing is 测试的线程是
static void DoInserts(object o)
{
int i = (int)o;
Console.WriteLine("Insert Thread {0} launched", i);
for(int x = 0; x < 1000; x++)
{
uint insertId = DataLayer.uNonQuery(String.Format("INSERT INTO testdb.dbtest (writeNo,strNo) VALUES ({0},'x={0} thread={1}')", x, i));
}
Console.WriteLine("Insert Thread {0} completed", i);
}
I get the exception Exception: Connection must be valid and open. 我收到异常异常:连接必须有效且打开。 after about 6 inserts on 2 concurrent threads, is there something else i need to do enable pooling to work correctly?
在2个并发线程上进行约6次插入后,我还需要做些其他事情来使池正常工作吗?
Thanks 谢谢
In your line using (Connection = new MySqlConnection(ConnectionString))
you are using the variable Connection
. 在
using (Connection = new MySqlConnection(ConnectionString))
中,使用变量Connection
。 Where is this variable defined? 该变量在哪里定义? Is it static?
它是静态的吗? You should define it in scope of
uNonQuery
. 您应该在
uNonQuery
范围内定义它。 If variable Connection
is static, then it is possible the connection is closed after a new function call to uNonQuery
has opened it. 如果变量
Connection
是静态的,则有可能在对uNonQuery
的新函数调用打开连接后关闭该连接。
Example: - Thread 1 calls uNonQuery
and opens, does it things. 示例:-线程1调用
uNonQuery
并打开,执行该操作。 - Thread 2 calls uNonQuery
, opens the connection, - Thread 1 closes Connection
- Thread 2 cannot do its thing because the connection was suddenly closed. -线程2调用
uNonQuery
,打开连接,-线程1关闭Connection
-线程2无法执行其操作,因为该连接突然关闭。
If the above is not the cause of your problem I would need more of your code to examine the problem. 如果以上不是导致问题的原因,则需要更多代码来检查问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.