使用Monitor线程插入查询时SQL中的死锁

时间:2013-09-17 10:49:48

标签: c# sql multithreading deadlock

出于某种原因,当我尝试运行SP以将即时数据插入数据库时​​,我遇到了死锁

使用此表的所有其他线程都正常工作。 当我通过SQL Server管理工作室手动向该表添加新行时,它释放锁并插入队列中的所有值

这是我的代码:

    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
            {
            }
        }

    }

1 个答案:

答案 0 :(得分:0)

问题是我没有关闭C#和SQL之间的通信。 国家是开放的标志,并被卡住了。 只有在重新开放沟通后问题才能解决。