Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BlockingCollection Max Size

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.

like image 528
maxfridbe Avatar asked Apr 10 '13 14:04

maxfridbe


People also ask

Is BlockingCollection thread-safe?

BlockingCollection<T> is a thread-safe collection class that provides the following features: An implementation of the Producer-Consumer pattern. Concurrent adding and taking of items from multiple threads.

What is a BlockingCollection C#?

What is a BlockingCollection? The BlockingCollection is a thread-safe collection in which you can have multiple threads add and remove data concurrently. It is represented in . Net through the BlockingCollection class; you can use this class to implement a producer-consumer pattern.

Is Blockcollection a FIFO?

That being said, BlockingCollection<T> works upon any IProducerConsumerCollection<T> (specified in the constructor). If you don't provide one in the constructor, internally, it will use a ConcurrentQueue<T> . This causes it to be FIFO, since it will actually be (internally) a queue.


1 Answers

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.

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

You would use this constructor and pass in a ConcurrentStack.

For example:

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

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

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.

like image 180
Matthew Watson Avatar answered Sep 21 '22 08:09

Matthew Watson