在发射事件之前等待/延迟

时间:2017-10-25 23:46:02

标签: c# msmq

我正在接收来自MSMQ的消息。收到消息时会触发事件,在某些情况下,在触发事件之前需要延迟。目前我有Task.Delay等待指定时间才能触发事件。我想知道是否有人有更好的解决方案,或者在我当前的解决方案中可以看到任何问题:

    private List<Task> _delayTasks = new List<Task>();

    private void PeekComplete(object sender, msmq.PeekCompletedEventArgs e)
    {
            //..code to get mesage off the queue...

            double delay = _messageTimeOut.TimeOutRequired(messageBody);

            if (delay > 0)
            {
                CreateDelayTask(delay, messageBody);
                WaitDelays();
            }
            else
            {
                _OnMessageReceived?.Invoke(messageBody);
                ProcessingCounter.Decrement();
            }

           GetNextMessage();

    }

    private void WaitDelays()
    {
        while (_delayTasks.Count > 0)
        {
            int index = -1;

            try
            {
                index = Task.WaitAny(_delayTasks.ToArray());
            }
            finally
            {
                if (index > -1)
                    _delayTasks.RemoveAt(index);
            }

        }
    }

    private void CreateDelayTask(double milliSecondsTimeOut, string messageBody)
    {
        var delay = (int)Math.Ceiling(milliSecondsTimeOut);

        var task = Task.Delay(delay).ContinueWith((antecedent) =>
         {
             try
             {
                 _OnMessageReceived?.Invoke(messageBody);
             }
             catch (Exception ex)
             {
                 _OnMessageReceivedError?.Invoke(ex, messageBody);
             }
             finally
             {
                 ProcessingCounter.Decrement();
             }
         });

        _delayTasks.Add(task);
    }

0 个答案:

没有答案