Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BlockingCollection or Queue<T> for jobs?

I am developing a windows forms application ( c# ), and while program is running, it creates objects adds them to a list. I have to process the items in the list , with FIFO ( first in first out ). I want to do this in a backgroundthread and i have to process them in order, number 1 , number 2, number 3 and so on. And as soon as an item gets added to the list i want to process it. So i have to have something to check that list.

What is the best way to achieve this?

I know that blockingcollection does something similar, that it waits for an item to be added before processing it.

I can use a single thread with the Queue and just while(true) and take items if there is any?

What do you think?

like image 840
syncis Avatar asked Aug 23 '11 12:08

syncis


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.


1 Answers

Sounds like you should go for the BlockingCollection<T> if you're planning on using a background thread. You can pretty easily do the same while(true) logic that you're looking for.

The BlockingCollection<T> gives you two important features

  1. It's thread-safe

  2. When you call Take(), it will block(i.e. wait until something is in the queue) for you, so you don't have to write any code with ManualResetEvents and the like, which is a nice simplification.

like image 124
Jonathan Beerhalter Avatar answered Oct 11 '22 02:10

Jonathan Beerhalter