Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Fix a CompareExchange Retry Loop That Spins Forever Because the Comparand Was Captured Before the Loop Started

- 10.10.26 - ErcanOPAK

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

— C# Best Practice

Related posts:

C#: Use Extension Methods to Add Functionality

C#: Use Extension Methods to Add Functionality

Boxing Happens Without You Noticing

Boxing Happens Without You Noticing

Events Can Cause Memory Leaks

Events Can Cause Memory Leaks

Views: 8

Post navigation

WordPress: Fix an admin-ajax Request That Returns 0 for Logged-Out Visitors Because Only wp_ajax_, Not wp_ajax_nopriv_, Was Registered
Windows 11: Fix a Storage Sense Policy That Deletes Downloads Files Earlier Than the Schedule You Actually Set

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com