使用 Parallel.For 时的限制 [英] throttling when using Parallel.For
问题描述
当使用单线程循环时,我可以很容易地通过将线程置于睡眠状态(即 Thread.Sleep(1000/MessagesPerSecond)
)来限制每秒发送的消息,这很简单.. 但现在我已经扩展到并行线程,这不再正常工作.
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);
});
推荐答案
使用 AutoResetEvent 和计时器.每当计时器触发时,让它Set
AutoResetEvent.
Use an AutoResetEvent and a timer. Whenever the timer fires, have it Set
the AutoResetEvent.
然后让您的进程在发送之前立即在 AutoResetEvent 上发送消息 WaitOne
.
Then have your process that sends messages WaitOne
on the AutoResetEvent immediately before sending.
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();
}
这篇关于使用 Parallel.For 时的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!