我有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.
为什么很多人使用使用方法,如果性能更差?还是我做错了?
解决方法
你是对的,打开连接是一个耗时的操作.为了减轻这一点,ADO.NET具有连接池.检查
this article的详细信息.
如果继续执行性能测试并检查后续连接的时间,应该会看到连接的时间.open()改进并接近0 ms,因为连接实际上是从池中获取的.
使用锁实现,您实际上只使用连接池连接.虽然这种方法可以在微不足道的测试中显示出更好的性能,但在高负载应用程序中将显示非常差的结果.