C# Parallel Programming: Working with Concurrent Collections — Part IV
From now, we saw three concurrent collections to use in our multitasking applications. Now let’s see how to create a producer and consumer tasks with BlockingCollection class.
As with other classes, The BlockingCollection can be found in System.Collections.Concurrent namespace. The code below presents a simple way to implement the BlockingCollection:
As you can note the code above starts with two tasks. The first one, or the producer, is responsible to add new Orders to the BlockCollection object.
All Order objects are added with BlockCollection.Add method. When the application finishes adding orders to the BlockCollection object, the method BlockCollection.CompleteAdding is called. Then the BlockCollection object is blocked for new items.
The second task, or the consumer, is responsible for taking items and presenting them to the user.
While the BlockCollection object is not empty, the application will get and remove an item from the collection, and present it to the user.
For checking if the collection is not empty, we can check if the property BlockCollection.IsCompleted is false. And for getting and removing items from the collection we can call the method BlockCollection.Take().
I hope that this can be helpful for you! HAPPY CODING!!
Ref.: