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

Luis Rodrigues
2 min readJan 4, 2022

--

In the last article, we saw how to work with ConcurrentQueue class. This time let’s see how to work with ConcurrentStack in our multitasking application.

Follow me on Twitter

The ConcurrentStack can be found in System.Collections.Concurrent namespace. Also, this structure is similar to the Stack class from System.Collections and System.Collections.Generic namespaces.

Just like the Stack class, a ConcurrentStack class allows us to work on “First In, Last Out” mode with different threads.

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

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

  • Push: adds a new item at the top from the Stack object.
  • TryPop: tries to get the first item at the top of the Stack object.

Note that the sum of all numbers was done from different threads in the Parallel.For loop, and once again we did not need to worry about the race condition problem in our multitasking application.

--

--

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/