I have a BlockingCollection which I write to from one thread and I read from another. The producer thread takes items received from a server and adds them to the BlockingCollection, while the reading thread attempts to empty the BlockingCollection and process them.
The problem I am trying to empty the queue in batches, because processing them one by one will be too slow. But when it's being constantly written to (thousands of items), then the consumer thread keeps reading them until it's emptied, which means that the processing will not even start until the writing is done.
Now, the processing in the consumer can be done in parallel, so I have been wondering how to go about that.
Currently I have 2 ideas:
After a certain number of items are read from the BlockingCollection in the consumer, start a new parallel job that processes them, instead of waiting to completely empty the queue and THEN start processing.
Use multiple consumers and hope that they will run in parallel instead of just constantly blocking each other while trying to read the BlockingCollection at the same time.
So my question is about option number 2 - is the BlockingCollection internally optimized for such a case? Will it partition the areas that are read from, or will the consumers fight over each item? If that's the case, then option 1 is superior?
But when it's being constantly written to (thousands of items), then the consumer thread keeps reading them until it's emptied, which means that the processing will not even start until the writing is done.
I have read that sentence multiple times and can't work out what it means. – mjwillsUse multiple consumers and hope that they will run in parallel instead of just constantly blocking each other while trying to read the BlockingCollection at the same time.
That is literally its job, so I presume it will be OK. But profile to be sure. If it is a problem, have a single consumer that batches entries intoList<entry>
and then adds them to a secondBlockingCollection
(that is consumed from by multiple readers) to reduce the contention. But honestly it is unlikely to be needed. – mjwills