使用 System.Collections.Concurrent.BlockingCollection 阻塞生产者,直到收集达到其容量的一半
我有一个使用 .NET 4.0
的新 BlockingCollection
实现的“单一生产者/单一消费者”场景。
问题是,一旦集合中有一个空间空闲,生产者线程就会被唤醒。我希望生产者阻塞,直到消费者消耗至少一半的集合项。这是因为生产者速度很高并且生产对于系统来说是昂贵的。
如何控制生产者的阻塞条件?
I have a "single producer/single consumer" scenario implemented with new BlockingCollection
of .NET 4.0
.
The problem is that the producer thread awakes as soon as there's as a single space beocmes free in the collection. I want the producer to block until the consumer consumes at least half of the collection items. This is because producer speed is high and producing is expensive to the system.
How can I control the blocking condition for the producer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种需要考虑的方法是排队较少的“较大”项目,而不是大量“小”单个项目。
例如,您可以将集合绑定为 1,并将项目类型更改为项目列表。通过这种方式,您的生产者可以生成 100 个项目的列表并将其排队,然后消费者将获取该列表并处理它,让生产者开始处理接下来的 100 个项目。这里的关键是,生产者将被优化,以便在被阻塞等待消费者完成之前,在一批中生产更大批量的数据。集合上的颠簸将会少得多,但生产和消费仍然会重叠。
当消费者取出 100 件商品的清单时,实际上是取出了未完成商品总数的一半,即 200 件商品。所以从概念上讲,这给了你你的阻塞条件。
An approach to consider is queuing fewer "bigger" items, rather than lots of "small" single items.
For example you could change the collection bound to 1 and change the item type to a list of items. In this way your producer could produce a list of 100 items and queue it, then the consumer would take this list and process it, leaving the producer to start on the next 100 items. The key here is that the producer will be optimized for producing larger batches of data in one batch before it is blocked waiting for the consumer to finish. There will be far less thrashing on the collection, but producing and consuming will still be overlapped.
When the consumer takes the list of 100 items, it is in effect taking half the total possible number of outstanding items i.e. 200 items. So conceptually this gives you your blocking condition.