问题
A consumer thread and multiple producer threads synchronize their work with a System.Collections.Concurrent.BlockingCollection<T>.
The producers call blockingCollection.Add()
and the consumer runsforeach (var item in blockingCollection.GetConsumingEnumerable()) {...}
Now one producer wants to "flush" the buffer: The producer wants to wait until all current items have been consumed. Other producers may add further items in the meantime, but this producer is only interested in the items that are currently in the queue.
How can I make the producer wait, without using busy waiting?
In essence I want some non-consumer threads to get notified whenever an item of the BlockingCollection is consumed .
I can set an AutoResetEvent in the consumer, but this will wake up only one thread waiting for changes, when there could be multiple:
foreach (var item in blockingCollection.GetConsumingEnumerable())
{
myAutoResetEvent.Set()
}
I can also set a ManualResetEvent:
foreach (var item in blockingCollection.GetConsumingEnumerable())
{
myManualResetEvent.Set()
}
This will wake up all waiting threads, but how would I switch it back off again?
回答1:
In case you end up using my comment
Put a dummy item in the collection that wakes up the producer
来源:https://stackoverflow.com/questions/30943042/observing-changes-in-a-blockingcollection-without-consuming