我目前使用ManualResetEvent为单个线程等待多个线程添加一些东西到一个线程管理器的队列。如果线程管理器使用手动重置事件接收到信号,它将使添加的项目出列并进行进一步处理。我唯一的问题是,如果有多个设置被触发,那么其他队列项目将不会被处理。 (见B点)ManualResetEvent大小检查是否足以等待多个线程?
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)事件。是否有其他课程用于此场景?
为什么不简单地改变你的第二,如果一段时间? – 2012-02-28 01:40:02