我实现了Producer消费者模型。当队列为空时,使用者应等待并再次检查队列。首先,我将其实现为Thread.Sleep(0),并且工作迅速。我将其更改为使用ManualResetEvent。当队列为空时,使用者等待_consumerEvent.WaitOne()。当Producer将元素放入队列时,它将设置ManualResetEvent。此解决方案的速度较慢,大约为30。有人可以解释原因吗?
var isPlaced = _producerConsumerQueue.Enqueue(work);
if (isPlaced)
{
_consumerEvent.Set();
break;
}
var isGetted = _producerConsumerQueue.TryDequeue(out work);
if (!isGetted)
{
// Wait of filling
_producerEvent.Set();
//Thread.Yield();
//Thread.Sleep(0);
_consumerEvent.WaitOne();
//Thread.SpinWait(1);
continue;
}