I have multiple producing threads, and single consuming. In C#, I'm using ConcurrentQueue
for that.
How can I properly put the consumer thread to sleep, when the queue is empty?
ManualResetEventSlim signal;
void WorkerThread(CancellationToken token)
{
while(!token.IsCancellationRequested)
{
object work;
if (!_eventQueue.TryDequeue(out work))
{
signal.Reset();
signal.Wait(token);
continue;
}
...
}
}
...
void Produce(object o)
{
_eventQueue.Enqueue(o);
signal.Set();
}
I tried this, but there is some chance, that
- thread B fails to read from
_eventQueue
- thread A writes into
_eventQueue
- thread A sets the signal
- thread B resets the signal
- thread B waits indefinitely
How to overcome this? Previously, I used lock()
and Monitor.Wait()
. AutoResetEvent
may help (it resets on successful Wait
), but it does not support CancellationToken
.