Observing changes in a BlockingCollection without consuming

只愿长相守 提交于 2019-12-24 14:28:17

问题


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 runs
foreach (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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!