C# Parallel Programming: Working with Concurrent Collections — Part II
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.
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.
I hope that this can be helpful for you! HAPPY CODING!!
Ref.: