如何在ThreadPool中同步执行函数?

时间:2013-10-17 09:56:43

标签: c# sync

我有Dictionary<string, Queue<Action>>,这个dict会动态添加数据,具体取决于数据库中是否有新数据。 现在Dictionary<string, Queue<Action>>中的数据如下所示:

"1",{A1,A2,A3,A4}
"2",{B1,B2,B3}
"3",{C1,C2}

我的程序将每隔10秒检查一次该字典并从字典中执行Dequeue操作,然后执行Invoke操作。执行角色如下:

  1. A1,B1,C1将首先执行。
  2. 如果A1结束,则开始执行A2;如果B1结束,则开始执行B2;如果C1结束,则开始执行C2;他们不需要等待另一个人的完成。
  3. 现在我的代码如下:

     //This function is to add new data into dictionary if data comes
     private void DoComparison(StuffEntity entity)
        {
            try
            {
                bool dataFlag = CheckIsNewData(entity.PickingTime, entity.WarningPeriod);
                if (dataFlag)  
                {
                    Action action = () => { DelaySendingMessageOut(entity); };
                    if (!QueueItem.ContainsKey(entity.FridgeID))
                    {
                        Queue<Action> queue = new Queue<Action>();
                        queue.Enqueue(action);
                        QueueItem.Add(entity.FridgeID, queue);
                    }
                    else
                    {
                        QueueItem[entity.FridgeID].Enqueue(action);
                    }
                }
            }
            catch (Exception ex)
            {
                CommonUnity.WriteLog(ex.Message);
                CommonUnity.WriteLog(ex.StackTrace);
            }
        }
    
    
      //This function is to check the Dictionary
      //And this function will be checked every 10 seconds.
        private void CheckingQueue()
        {
            foreach (KeyValuePair<string, Queue<Action>> kvp in QueueItem)
            {
                string fridgeID = kvp.Key;
                Queue<Action> queue = kvp.Value;
    
                ThreadPool.QueueUserWorkItem((_) =>
                {
                    if (queue.Count > 0)
                    {
                       //How can I know that the previous work has been finished?
                        queue.Dequeue().Invoke();
                    }
                });
            }
        }
    

    修改

    enter image description here

    THX。 为此,我有一个解决方案,创建3个线程并使用AutoResetEvent数组来同步队列执行。但如果dict中有数以千计的物品,那将不是一个好主意。

    这是DelaySendingMessageOut函数的代码:

    private void DelaySendingMessageOut(StuffEntity entity)
        {
            int pendingPeroid = entity.PendingTime.ToInt();
            if (pendingPeroid <= 0)
                pendingPeroid = 5; 
    
            Thread.Sleep(pendingPeroid * 60 * 1000); //delay sending
    
            TriggerCheckingBeforeSendMessageOut(entity);
        }
    

0 个答案:

没有答案
相关问题