🔍 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

✅ Why Use Interlocked?

🧵 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

🏁 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.