csharp / expert
Snippet
Atomic State Management with Compare-And-Swap
The Interlocked.CompareExchange method implements a Compare-And-Swap (CAS) operation, which is the foundation of lock-free concurrency. It atomically checks if a value matches an expected one and, if so, replaces it. This avoids the overhead of traditional locks (mutexes) and prevents thread context switching, which is critical for high-throughput systems.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System.Threading;public class LockFreeStack{private int _state = 0;public void UpdateState(int expected, int next){// Spin-wait using CompareExchange for lock-free thread safetywhile (Interlocked.CompareExchange(ref _state, next, expected) != expected){// Potential back-off logic hereThread.Yield();}}}
Breakdown
1
while (Interlocked.CompareExchange(ref _state, next, expected) != expected)
Attempts to update the state only if the current value matches 'expected' in a single atomic step.
2
Thread.Yield();
Allows other threads to execute if the atomic update fails due to contention.