When using a single threaded loop, I was easily able to limit my messages sent per second by putting the thread to sleep (i.e. Thread.Sleep(1000/MessagesPerSecond)), easy enough… but now that I have expanded into parallel threads this no longer works correctly.
Does anyone have a suggestion how to throttle messages sent when using Parallel threads?
Parallel.For(0, NumberOfMessages, delegate(int i) {
// Code here
if (MessagesPerSecond != 0)
Thread.Sleep(1000/MessagesPerSecond);
});
Use an AutoResetEvent and a timer. Whenever the timer fires, have it
Setthe AutoResetEvent.Then have your process that sends messages
WaitOneon the AutoResetEvent immediately before sending.