C# Interview Question #113
What is Interlocked in C#?
Concurrency, Performance & Design Senior Advanced
Quick Interview Answer
Interlocked provides atomic operations for simple shared variables without requiring a traditional lock.
Detailed Explanation
Interlocked provides atomic operations for simple shared variables without requiring a traditional lock.
Common operations include Increment, Decrement, Exchange, CompareExchange, Add, and Read. These operations are useful for counters, flags, and certain lock-free coordination patterns.
Interlocked is appropriate only when the required state transition can be expressed through its atomic operations. More complex invariants may still require locks or another synchronization strategy.
Code Example
private int _requestCount;
public void RecordRequest()
{
Interlocked.Increment(ref _requestCount);
}