Thread-safe stacks in .NET
July 7, 2015 3 Comments
We saw how Stacks work in .NET in this post. Stacks are last-in-first-out collections where the last element added to the collection will the first to be removed.
If you’d like to have a Stack that is shared among multiple threads in a multi-threaded application then the “normal” Stack of T object won’t be enough. You can never be sure of the current state of the stack in the very moment when a certain thread tries to pop an item from it. The stack may have been modified by another thread just a millisecond before and then the Pop method will fail. In general you should be very careful with how you share the resources among different threads.
The Stack object has a thread-safe equivalent in .NET called ConcurrentStack which resides in the System.Collections.Concurrent namespace. Here’s some important terminology:
- Adding an item is called a push just like in the case of the single-threaded Stack object
- The Pop method has been replaced with TryPop which returns false in case there was nothing to retrieve from the stack. If it returns true then the popped item is returned as an “out” parameter
- Similarly the Peek method has been replaced with TryPeek which works in an analogous way
The following code fills up a stack of integers with 1000 elements and starts 4 different threads that all read from the shared stack.
public class ConcurrentStackSampleService { private ConcurrentStack<int> _integerStack = new ConcurrentStack<int>(); public void RunConcurrentStackSample() { FillUpStack(1000); Task readerOne = Task.Run(() => GetFromStack()); Task readerTwo = Task.Run(() => GetFromStack()); Task readerThree = Task.Run(() => GetFromStack()); Task readerFour = Task.Run(() => GetFromStack()); Task.WaitAll(readerOne, readerTwo, readerThree, readerFour); } private void FillUpStack(int max) { for (int i = 0; i <= max; i++) { _integerStack.Push(i); } } private void GetFromStack() { int res; bool success = _integerStack.TryPop(out res); while (success) { Debug.WriteLine(res); success = _integerStack.TryPop(out res); } } }
Each thread will try to pop items from the shared stack as long as TryPop returns false. In that case we know that there’s nothing more left in the collection.
View the list of posts on the Task Parallel Library here.
Reblogged this on Dinesh Ram Kali..
Reblogged this on Brian By Experience.
Pingback: Summary of thread-safe collections in .NET – .NET training with Jead