Thread-Safe Counters and Flags Using Interlocked in .NET

🔍 What is Interlocked In .NET?

In multithreaded applications, multiple threads can access and modify shared variables concurrently. This can lead to race conditions. The System.Threading.Interlocked class provides atomic operations on variables, ensuring thread safety without using locks.

🧮 Common Use Cases

  • Counters (Increment/Decrement)
  • Flags (Boolean states)
  • Exchange operations
  • Compare-and-swap (CAS)

✅ Why Use Interlocked?

  • Atomic operations: Guaranteed to complete without interruption
  • Lightweight: Faster than locking mechanisms
  • Lock-free: Reduces the chance of deadlocks

🧵 Thread-Safe Counter Example

using System;
using System.Threading;

class Program
{
    private static int counter = 0;

    static void Main()
    {
        Thread[] threads = new Thread[10];

        for (int i = 0; i < threads.Length; i++)
        {
            threads[i] = new Thread(() =>
            {
                for (int j = 0; j < 1000; j++)
                {
                    Interlocked.Increment(ref counter);
                }
            });
            threads[i].Start();
        }

        foreach (var t in threads) t.Join();

        Console.WriteLine($"Final counter value: {counter}");
    }
}

🔁 Methods in Interlocked

  • Interlocked.Increment(ref int location)
  • Interlocked.Decrement(ref int location)
  • Interlocked.Add(ref int location, int value)
  • Interlocked.Exchange(ref T location, T value)
  • Interlocked.CompareExchange(ref T location, T value, T comparand)

🏁 Thread-Safe Flag Example (Boolean)

Booleans aren't directly supported by Interlocked, but you can simulate them using integers:

private static int isRunning = 0;

if (Interlocked.CompareExchange(ref isRunning, 1, 0) == 0)
{
    try
    {
        // Do work
    }
    finally
    {
        Interlocked.Exchange(ref isRunning, 0);
    }
}

Summary

Interlocked is ideal for low-level concurrency control. Best for simple shared variable updates. Use it when you want lock-free synchronization. For complex data structures, prefer lock or concurrent collections.

Up Next
    Ebook Download
    View all
    DateTime in C#
    Read by 1.3k people
    Download Now!
    Learn
    View all