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

Luis Rodrigues
2 min readJan 3, 2022

--

How can we work safely with collections through Parallel Programming with C#? In this series let’s see what .NET offers as thread-safe collections.

Follow me on Twitter

If you want to work with collection in multitasking applications, take a look at System.Collections.Concurrent namespace. This namespace provides corresponding types from System.Collections and System.Collections.Generic namespaces.

In this first part, let’s see how to use the ConcurrentQueue class. Just like the Queue class, ConcurrentQueue objects allow us to work on “First In, First Out” mode with different threads.

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

Basically, the code above will sum all numbers within from concurrent queue object. There are two important methods here to handle a ConcurrentQueue:

  • Enqueue: adds a new object to the end of the queue.
  • TryDequeue: tries to remove and return the object of the queue.

Note that the sum of all numbers was done for different threads in the Parallel.For loop.

Now, If you want to use the simple Queue object in a multitasking application, you will need to worry about handling the race condition problem.

In the code below, we are using the Monitor object to handle the concurrency when trying to dequeue all items:

--

--

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/