C# Parallel Programming: Working with Concurrent Collections — Part IV

Luis Rodrigues
2 min readJan 6, 2022

--

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.

Follow me on Twitter

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().

--

--

Luis Rodrigues
Luis Rodrigues

Written by Luis Rodrigues

A software engineer who in his spare time undertakes and creates articles for the tech community — https://www.linkedin.com/in/sw-luis-rodrigues/