Thread-safe stacks in .NET

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

3 Responses to Thread-safe stacks in .NET

  1. Brian Dead Rift Webb says:

    Reblogged this on Brian By Experience.

  2. Pingback: Summary of thread-safe collections in .NET – .NET training with Jead

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: