BlockingCollection 最大尺寸 [英] BlockingCollection Max Size

查看:25
本文介绍了BlockingCollection 最大尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用 ConcurrentQueue 的 BlockingCollection 的有界容量为 100.

I understand that BlockingCollection using ConcurrentQueue has a boundedcapacity of 100.

但是我不确定这意味着什么.

However I'm unsure as to what that means.

我正在尝试实现一个并发缓存,如果队列大小太大,它可以出队,可以出队/入队,如果队列过大,(即缓存溢出时松散的消息).有没有办法为此使用有界容量,或者最好手动执行此操作或创建新集合.

I'm trying to achieve a concurrent cache which, can dequeue, can deque/enque in one operation if the queue size is too large, (i.e. loose messages when the cache overflows). Is there a way to use boundedcapacity for this or is it better to manually do this or create a new collection.

基本上我有一个阅读线程和几个写作线程.如果队列中的数据是所有作者中最新鲜"的,我会很高兴.

Basically I have a reading thread and several writing threads. I would like it if the data in the queue is the "freshest" of all the writers.

推荐答案

有界容量 N 意味着如果队列已经包含 N 个项目,任何尝试添加另一个项目的线程都会阻塞,直到另一个线程删除一个项目.

A bounded capacity of N means that if the queue already contains N items, any thread attempting to add another item will block until a different thread removes an item.

您似乎想要的是一个不同的概念 - 您希望最近添加的项目成为消费线程出队的第一个项目.

What you seem to want is a different concept - you want most recently added item to be the first item that is dequeued by the consuming thread.

您可以通过使用 ConcurrentStack 而不是底层存储的 ConcurrentQueue.

You can achieve that by using a ConcurrentStack rather than a ConcurrentQueue for the underlying store.

您将使用这个构造函数并传入一个 ConcurrentStack.

例如:

var blockingCollection = new BlockingCollection<int>(new ConcurrentStack<int>());

通过使用ConcurrentStack,您可以确保消费线程出列的每个项目都是当时队列中最新鲜的项目.

By using ConcurrentStack, you ensure that each item that the consuming thread dequeues will be the freshest item in the queue at that time.

另请注意,如果您为阻止集合指定上限,则可以使用 BlockingCollection.TryAdd() 如果在您调用它时集合已满,它将返回 false.

Also note that if you specify an upper bound for the blocking collection, you can use BlockingCollection.TryAdd() which will return false if the collection was full at the time you called it.

这篇关于BlockingCollection 最大尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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