Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to BlockingCollection after CompleteAdding is called

Tags:

c#

.net-4.0

I'm using a Producer-Consumer pattern and I use a BlockingCollection that produces data and consumes data from it. I call a method to produce the data and then set the BlockingCollection to CompleteAdding so that the consumer consumes all the data from the BlockingCollection. After some processing the application wants to add some other data to the BlockingCollection, but it can't because it is set to CompleteAdding, how can I set CompleteAdding to false, or how can I consume all the data from the BlockingCollection, not waiting for the ComleteAdding?

like image 868
XandrUu Avatar asked Aug 30 '12 10:08

XandrUu


People also ask

What is a BlockingCollection?

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. Optional maximum capacity. Insertion and removal operations that block when collection is empty or full.

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.

How to use BlockingCollection c#?

If you want to add elements to a BlockingCollection<T> in C#, then you need to use the following methods of the BlockingCollection<T> class. Add(T item): This method is used to add the item to the BlockingCollection. Add method takes a single parameter i.e. the item to be added to the collection.


1 Answers

You can't - the whole point of calling CompleteAdding is to say, "There will never be any more data added to this collection. Once it's empty, you know you're done." What you're asking for is a bit like saying, "After I've closed a network connection, how can I reopen it so I can write more data?"

The fact that you want to suggests you should rethink your design. Perhaps you should be creating a new BlockingCollection at this point instead? Or perhaps you don't really want to call CompleteAdding to start with?

like image 163
Jon Skeet Avatar answered Nov 15 '22 17:11

Jon Skeet