🔧 The Retry Loop That Never Saw Its Own Progress
A compare-and-swap loop built on Interlocked.CompareExchange is supposed to keep retrying with a freshly read value until it successfully swaps in a new one, which only works if the comparand passed to CompareExchange is re-read at the top of every single iteration. Hoisting that read outside the loop – capturing the field’s value once before the loop begins instead of once per attempt – leaves every retry comparing against the same stale snapshot forever. The very first failed attempt guarantees every attempt after it will also fail, because the field’s real current value can never again equal that one frozen comparand, and the loop spins at full CPU with no way to ever exit on its own.
🔎 The Problem
private int _version;
public void Bump()
{
// BUG: captured once, before the loop - should be re-read on
// every iteration, not just the first one.
int initial = _version;
int computed;
do
{
computed = initial + 1;
// On the first failed attempt, _version is no longer equal
// to "initial" - but "initial" itself never gets updated,
// so every subsequent comparison is guaranteed to fail too.
} while (Interlocked.CompareExchange(ref _version, computed, initial) != initial);
}
// Under light load, one thread usually wins on the first try and
// nobody notices anything wrong. Under real contention, the second
// thread to lose a single race spins here forever, burning a core.
✅ Fix: Re-Read the Comparand Inside Every Iteration
- Move the read of the field being updated inside the loop body itself, so every retry compares against the field’s actual current value rather than a value captured once before the loop ever started.
- Review every CompareExchange retry loop in the codebase specifically for where the comparand variable is assigned, since the bug is purely about placement – the surrounding logic can look completely correct otherwise.
- Add a concurrency test that runs several threads against the same CAS loop simultaneously and asserts the method actually returns within a bounded time, since a single-threaded test can never expose a retry bug that only manifests under contention.
⚠️ Why This Is Easy to Miss
- Works perfectly under light or no contention, because the very first attempt usually succeeds before any other thread has touched the field, so the stale-comparand path never actually executes in casual testing.
- The code reads correctly at a glance because every textbook example of this pattern looks almost identical – the only difference is one line’s position relative to the loop, which is easy to get wrong while refactoring without changing the method’s apparent structure.
A compare-and-swap loop that never refreshes what it’s comparing against isn’t retrying anything – it’s just repeating the same guaranteed failure as fast as the CPU will let it.

