Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

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

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
C#

C#: Fix a Volatile Field Reordered Around a Non-Volatile Read

- 30.11.26 - ErcanOPAK

🔧 Fix a Volatile Field Reordered Around a Non-Volatile Read

Marking a single field volatile only guarantees ordering and visibility for reads and writes of that one field — the JIT and the CPU are still free to reorder reads of other, non-volatile fields around it, so a common pattern of ‘check a volatile flag, then read a related non-volatile field’ doesn’t actually guarantee the non-volatile read sees the value that was written before the flag was set, on architectures with weaker memory ordering than x86.

🔎 The Problem

private volatile bool _ready;
private int _cachedResult; // NOT volatile

public void Producer()
{
    _cachedResult = ComputeExpensive();
    _ready = true; // volatile write
}

public int Consumer()
{
    if (_ready) // volatile read
        return _cachedResult; // NOT guaranteed to see the write above
    return -1;
}

✅ Fix: Use a Real Memory Barrier, Not Just One Volatile Flag

  • Replace the manual flag-and-field pattern with Interlocked.CompareExchange or a full fence via Thread.MemoryBarrier() around both the write and the read, which guarantees ordering for every field involved, not just the one marked volatile.
  • Where the value only needs to be published once and read many times, consider Lazy<T> with thread-safety mode ExecutionAndPublication, which handles the memory barrier correctly without hand-rolled flag logic.
  • If you specifically need a single reference published safely, Volatile.Write/Volatile.Read on the reference itself (rather than a separate bool flag) ties the barrier directly to the value that matters.

🚨 Why This Is Dangerous

  • This bug is effectively invisible on x86/x64 in normal testing because its strong memory model hides the reordering — it tends to surface only under real contention on ARM or in a stress test specifically designed to catch it.

Volatile orders one field’s reads and writes — it was never a promise about anything sitting next to it in memory.

— C# Best Practice

Related posts:

C#: Use Async/Await for Asynchronous Programming

C#: Use Async/Await for Asynchronous Programming

Using Code Blocks, Mixing Text & C# Code and Comments in Asp.NET MVC Razor

Using Code Blocks, Mixing Text & C# Code and Comments in Asp.NET MVC Razor

C#: Fix a TaskCompletionSource Deadlock Caused by a Continuation That Runs Synchronously on the Thre...

C#: Fix a TaskCompletionSource Deadlock Caused by a Continuation That Runs Synchronously on the Thre...

Views: 6
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

Docker: Fix Compose Health Checks Never Reaching Healthy
JavaScript: Fix a Generator Function Leaking Across Iterations

Leave a Reply Cancel reply

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

Most Read

  1. 01How to make theater mode the default for Youtube 1,080 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 999 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 998 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 874 views
  5. 05How to select distinct rows in a datatable in C# 869 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 673 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 632 views
  8. 08Average of all values in a column that are not zero in SQL 586 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 563 views
Bits of .NET

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

Social

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