【发布时间】:2012-02-28 09:43:25
【问题描述】:
我目前正在为单个线程使用 ManualResetEvent 来等待多个线程将某些内容添加到线程管理器的队列中。如果线程管理器使用手动重置事件接收到信号,它将使添加的项目出列并进行进一步处理。我唯一的问题是,如果触发了多个集合,则不会处理其他队列项。 (见B点)
while (IsThreadRunning)
{
// A: My workaround is to check if queue has item, if not then wait for other thread to set the event
if (DataQueue.Count <= 0)
{
ResetEvent.WaitOne();
}
// B: At this point two thread added item to the queue and did ResetEvent.Set() twice.
if (DataQueue.Count > 0)
{
DataQueue.Dequeue();
}
// Reset the event to avoid processor hog
ResetEvent.Reset();
}
我的解决方法是在 A 点 上添加队列大小条件。 有没有其他方法可以避免死锁?
注意:在使用 ManualResetEvent 的示例中给出的通常场景是单个线程上有多个线程等待(ManualResetEvent.Wait)事件,但这里是多个线程触发(ManualResetEvent.Set)事件。是否有其他类用于此场景?
【问题讨论】:
-
为什么不把你的第二个换成一段时间呢?
标签: c# multithreading manualresetevent