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

Luis Rodrigues
2 min readJan 5, 2022

--

In our last article, we saw how to work with the ConcurrentStack class. Now let’s see how to handle concurrency with ConcurrentBag in our multitasking application.

Follow me on Twitter

The ConcurrentBag can be found in System.Collections.Concurrent namespace, and different from ConcurrentStack and ConcurrentQueue, this structure does not follow any order to store objects.

The code below presents a simple way to implement the ConcurrentBag:

First, with ConcurrentBag.Add method, some numbers were added in the ConcurrentBag object through Parallel.For. Note that at this moment different threads were created to populate the ConcurrentBag object.

Then, the next step is to simulate concurrent operations with two tasks when getting items and cleaning the ConcurrentBag object. Each task will call the ConcurrentBag.TryTake method to get and remove the item from the ConcurrentBag object.

Finally, with Task.WaitAll method, the application runs those tasks in parallel to present the values and clean the ConcurrentBag object.

--

--

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/