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?
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.
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
It's thread-safe
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.
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