0

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 の実行を開始します。別の完了を待つ必要はありません。

今私のコードは以下のようなものです:

 //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();
                }
            });
        }
    }

編集:

ここに画像の説明を入力

どうも。このために、解決策があり、3 つのスレッドを作成し、AutoResetEvent 配列を使用してキューの実行を同期します。しかし、辞書に何千もの項目がある場合は良い考えではありません。

これは 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);
    }
4

0 に答える 0