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.

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

--

--

A software engineer who in his spare time undertakes and creates articles for the tech community — https://twitter.com/iamluisrod

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Luis Rodrigues

A software engineer who in his spare time undertakes and creates articles for the tech community — https://twitter.com/iamluisrod