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
?
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With