Interlocked Class in C#: What It Is and How to Use It
Interlocked class in C# provides atomic operations for variables shared between multiple threads, ensuring thread safety without using locks. It helps prevent race conditions by making operations like increment, decrement, and exchange happen as a single, uninterruptible step.How It Works
The Interlocked class works by performing operations on variables in a way that cannot be interrupted by other threads. Imagine you and a friend are both trying to update the same bank account balance at the same time. Without coordination, you might both read the same balance and write back conflicting amounts, causing errors.
Interlocked acts like a teller who makes sure only one person updates the balance at a time, completing the entire operation before the next person can start. This prevents mistakes called race conditions, where multiple threads interfere with each other.
It provides simple methods like incrementing or exchanging values atomically, meaning the operation is done fully or not at all, without any partial updates visible to other threads.
Example
This example shows how to safely increment a shared counter from multiple threads using Interlocked.Increment. It ensures the count is correct even when many threads update it at the same time.
using System; using System.Threading; class Program { private static int counter = 0; static void Main() { Thread[] threads = new Thread[5]; 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}"); } }
When to Use
Use the Interlocked class when you need to update shared variables safely across multiple threads without the overhead of locks. It is ideal for simple operations like incrementing counters, swapping values, or adding numbers where you want fast, thread-safe updates.
For example, in a web server counting active users or in a game tracking scores updated by many players at once, Interlocked ensures the data stays accurate without slowing down the program with complex locking.
Key Points
- Atomic operations:
Interlockedmethods complete fully without interruption. - Thread safety: Prevents race conditions on shared variables.
- Performance: Faster than using locks for simple operations.
- Common methods: Increment, Decrement, Exchange, CompareExchange.
- Use cases: Counters, flags, simple shared data updates.