Search code examples
c#.netcollectionsjobs

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?


Solution

  • 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.