【发布时间】:2018-12-06 09:51:49
【问题描述】:
我有一个多线程应用程序,其中 N 个线程正在访问 MySQL 数据库。每个查询都会创建自己的 MySqlConnection 实例以避免共享 MySqlDataReader。 但是,我们的数据库服务器遇到 CPU 峰值。 我已经尝试运行 SHOW PROCESSLIST 但结果中没有慢查询。我怀疑根本原因是线程如何处理连接。
以下是我的查询方法示例。
public List<Configuration> GetAlertConfigByDeviceID(string deviceID)
{
List<Configuration> configurations = new List<Configuration>();
try
{
using (MySqlConnection dbConnection = new MySqlConnection(WinAlerterConfig.WebConnectionString))
{
dbConnection.Open();
using (MySqlCommand dbCommand = dbConnection.CreateCommand())
{
dbCommand.CommandText = StoredProcedures.SqlGetAlertCfgDetailByDeviceID;
dbCommand.Parameters.Add(new MySqlParameter("DeviceID", deviceID));
using (MySqlDataReader dbResultSet = dbCommand.ExecuteReader())
{
if (dbResultSet.HasRows)
{
while (dbResultSet.Read())
{
configurations.Add(new Configuration()
{
ConfigID = dbResultSet.GetUInt64Safe(0),
AlertType = dbResultSet.GetUInt64Safe(1),
ZoneID = dbResultSet.GetUInt64Safe(2),
Timeout = dbResultSet.GetInt64Safe(3),
DeviceID = dbResultSet.GetStringSafe(4),
FromZoneID = dbResultSet.GetUInt64Safe(5),
OtherZoneAlert = dbResultSet.GetBooleanSafe(6),
Remarks = dbResultSet.GetStringSafe(7)
});
}
}
dbResultSet.Close();
dbResultSet.Dispose();
}
dbCommand.Dispose();
}
dbConnection.Close();
dbConnection.Dispose();
}
}
catch (MySqlException ex)
{
Logger.LogErrorLine("GetAlertConfigByDeviceID: {0} {1} {2}", ex.Message, Environment.NewLine, ex.StackTrace);
}
catch (Exception ex)
{
Logger.LogErrorLine("GetAlertConfigByDeviceID: {0} {1} {2}", ex.Message, Environment.NewLine, ex.StackTrace);
}
return configurations;
}
我还在我们的连接字符串中包含了 "polling = true;"。所以我假设 MySQL 或 ADO.net 将处理连接池。
我的方法做错了吗? ADO.net 是否已经处理了连接池?
【问题讨论】:
标签: c# mysql multithreading windows-services