Throttling when using Parallel.For

When using a single threaded loop, I could easily limit my messages sent per second by putting the thread to sleep (i.e. Thread.Sleep(1000/MessagesPerSecond)) quite easily ... but now that I have expanded the parallel threads, it no longer works correctly.

Does anyone have a suggestion on how to throttle messages sent using parallel streams?

Parallel.For(0, NumberOfMessages, delegate(int i) {

   // Code here

   if (MessagesPerSecond != 0)
      Thread.Sleep(1000/MessagesPerSecond);
});
+3
source share
2 answers

Use AutoResetEvent and a timer. Whenever a timer fires, use Setthe AutoResetEvent parameter.

WaitOne AutoResetEvent .

    private static readonly AutoResetEvent _Next = new AutoResetEvent(true);
    private static Timer _NextTimer;

    private static void SendMessages(IEnumerable<Message> messages)
    {
        if (_NextTimer == null)
            InitializeTimer();

        Parallel.ForEach(
            messages,
            m =>
            {
                _Next.WaitOne();
                // Do something
            }
            );
    }

    private static void SetNext(object state)
    {
        _Next.Set();
    }
+4

, ConcurrentQueue, . System.Threading.Timer, . , , ; , .

, , , . , , - " ", , . , ( ) BlockingCollection.

+2

Source: https://habr.com/ru/post/1754460/


All Articles