我有TcpListener类,我正在使用async / await阅读和写作.
对于这个服务器,我创建了单个数据库实例,我准备了所有的数据库查询.
但是对于更多的TcpClient,我会不断得到异常:
An exception of type
MySql.Data.MySqlClient.MysqLException
occurred
inMysqL.Data.dll
but was not handled in user codeAdditional information: There is already an open
DataReader
associated
with thisConnection
which must be closed first.
如果我理解正确,则不能再有一个数据库查询在时间上是多个异步客户端的问题.
// One MysqLConnection instance for whole program. lock (thisLock) { var cmd = connection.CreateCommand(); cmd.CommandText = "SELECT Count(*) FROM logins WHERE username = @user AND password = @pass"; cmd.Parameters.AddWithValue("@user",username); cmd.Parameters.AddWithValue("@pass",password); var count = int.Parse(cmd.ExecuteScalar().ToString()); return count > 0; }
我也尝试使用这种方法,它为每个查询创建新的连接,如从SO社区的人那里提到的,但是这种方法比锁更慢:
using (MysqLConnection connection = new MysqLConnection(connectionString)) { connection.Open(); // This takes +- 35ms and makes worse performance than locks using (MysqLCommand cmd = connection.CreateCommand()) { cmd.CommandText = "SELECT Count(*) FROM logins WHERE username = @user AND password = @pass"; cmd.Parameters.AddWithValue("@user",username); cmd.Parameters.AddWithValue("@pass",password); int count = int.Parse(cmd.ExecuteScalar().ToString()); return count > 0; } }
我使用秒表来测试这种方法和查询,一个连接与锁是在 – 20ms执行,这是 – 只有网络的延迟,但使用它是 – 55ms,因为.Open()方法 – 35ms.