出于某种原因,当我尝试运行 SP 以将即时数据插入数据库时出现死锁
使用此表的所有其他线程都工作正常。当我通过 SQL Server Management Studio 手动向该表添加新行时,它会释放锁并插入队列中的所有值
这是我的代码:
Queue<IDbCommand> instatntDataCmdQ;
public void ExecuteInstantDataCmd(int channel, DateTime date, double val, int status)
{
System.Data.SqlClient.SqlCommand cmd = GetInstantDataCmd( channel, date, val, status);
lock (instatntDataCmdQ)
{
try
{
instatntDataCmdQ.Enqueue(cmd);
Monitor.Pulse(instatntDataCmdQ);
}
catch
{
}
}
}
void thInstantDataRun()
{
instatntDataCmdQ = new Queue<IDbCommand>(100);
while (true)
{
try
{
IDbCommand cmd;
lock (instatntDataCmdQ)
{
if (instatntDataCmdQ.Count == 0)
Monitor.Wait(instatntDataCmdQ);
if (instatntDataCmdQ.Count == 0 || (cmd = instatntDataCmdQ.Dequeue()) == null)
break;
}
try
{
//open connection.
if (cmd.Connection.State == ConnectionState.Closed)
cmd.Connection.Open();
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Close();
cmd.Connection.Open();
}
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException dex)
{
AddDBlog(cmd.Connection, "thInstantDataRun",
"Critical error, duplicate dateTime&channel in InstantData table\r\n" + dex.Message);
}
catch (Exception err)
{
AddDBlog(cmd.Connection, "thInstantDataRun", "Error Executing Command " + err.Message);
}
finally
{
//do not close connection
//this some time will take up to 1 second and will make the insert of the isntant slow
// cmd.Connection.Close();
cmd.Dispose();
cmd = null;
}
}
catch
{
}
}
}