观察BlockingCollection中的更改而无需消耗 [英] Observing changes in a BlockingCollection without consuming

查看:83
本文介绍了观察BlockingCollection中的更改而无需消耗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用者线程和多个生产者线程将其工作与 System.Collections.Concurrent.BlockingCollection<T> .

A consumer thread and multiple producer threads synchronize their work with a System.Collections.Concurrent.BlockingCollection<T>.

生产者致电blockingCollection.Add()
消费者运行
foreach (var item in blockingCollection.GetConsumingEnumerable()) {...}

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?

本质上,我希望每当BlockingCollection的一项被消耗时,一些非消费者线程就会得到通知.

我可以在使用者中设置一个AutoResetEvent,但是在可能有多个线程的情况下,这只会唤醒一个等待更改的线程:

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()
}

我还可以设置一个ManualResetEvent:

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?

推荐答案

以防您最终使用我的评论

In case you end up using my comment

在集合中放置一个虚拟物品,该物品会唤醒生产者

Put a dummy item in the collection that wakes up the producer

这篇关于观察BlockingCollection中的更改而无需消耗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆