以下代码使用后台工作线程逐个处理工作项目。只要工作项目用完,工作线程就会开始等待ManualResetEvent。主线程定期添加新的工作项并唤醒工作线程。C#工作线程唤醒竞争条件
醒来机制有竞争条件。如果主线程添加新项目,而工作线程位于*指定的位置,则工作线程不会被唤醒。
是否有一种简单且正确的方法来唤醒没有此问题的工作线程?
ManualResetEvent m_waitEvent;
// Worker thread processes work items one by one
void WorkerThread()
{
while (true)
{
m_waitEvent.WaitOne();
bool noMoreItems = ProcessOneWorkItem();
if (noMoreItems)
{
// *
m_waitEvent.Reset(); // No more items, wait for more
}
}
}
// Main thread code that adds a new work item
AddWorkItem();
m_waitEvent.Set(); // Wake worker thread
'System.Collections.Concurrent.ConcurrentQueue'' System.Collections.Concurrent.BlockingCollection' – I4V