CodeBlanks Logo Icon CodeBlanks

ConcurrentStack

C# course · Expert · Lesson 27/47

Learn the thread-safe stack with ConcurrentStack.

ConcurrentStack

ConcurrentStack<T> is a thread-safe last-in-first-out (LIFO) stack. You Push onto the top and TryPop from the top. The internals are again a lock-free linked list.

It fits backtracking, undo, or task stacks where the most recently pushed item is processed first. When the same thread pushes and pops, a local top cache makes it very fast.

PushRange and TryPopRange

PushRange(T[] items) pushes many items at once onto the top; it is more efficient than calling Push for each. TryPopRange(T[] items) pops as many items as fit into an array from the top.

In batch work these methods cut the internal synchronization overhead. For single items, Push and TryPop are enough.

Exercise Push and pop the stack

The stack below is empty. Use Push to add three items: "1", "2", "3". Then loop with while (stack.TryPop(out var item)) and print each item. LIFO order means the output is 3, 2, 1.

Show example solution
stack.Push("1"); stack.Push("2"); stack.Push("3"); Then while (stack.TryPop(out var item)) Console.WriteLine(item);
Example solution:
using System;
using System.Collections.Concurrent;

class Program
{
    static void Main()
    {
        var stack = new ConcurrentStack<string>();
        stack.Push("1");
        stack.Push("2");
        stack.Push("3");
        while (stack.TryPop(out var item))
        {
            Console.WriteLine(item);
        }
    }
}

Test yourself

  1. Match each stack method

    Push
    Add to top
    TryPop
    Remove from top
    TryPeek
    Look at top without removing
  2. Complete the Push call

    stack.____;
    Show answer
    stack.Push("first");
  3. What is the ordering behavior of ConcurrentStack?

    • LIFO (last in first out)
    • FIFO (first in first out)
    • Sorted
    • Unordered
    Show answer

    LIFO (last in first out) — Correct. ConcurrentStack is LIFO: last pushed pops first.

All lessons in Expert