C# Reference ยท Keywords and Statements
The volatile keyword
Reference for the C# volatile keyword: what it guarantees for fields shared between threads, what it does not, and when to use lock or Volatile.Read instead.
volatile is a modifier for fields. It marks a field as one that other threads may change at any moment, so the compiler, the JIT and the CPU must not cache it in a register or reorder accesses to it in a way that would hide those changes. Reads of a volatile field have acquire semantics and writes have release semantics.
It is a narrow tool. It works for simple flags and published references ("the other thread sets stop, this thread sees it"), and it does nothing to make compound operations such as count++ atomic. For anything beyond a flag, use lock, Interlocked or a concurrent collection.
private volatile bool _stopRequested;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
private volatile int _state; private volatile Config? _config;
| Part | Description |
|---|---|
| Allowed types | Reference types, pointers (unsafe), sbyte, byte, short, ushort, int, uint, char, float, bool, nint, nuint, and enums with one of those underlying types. |
| Not allowed | long, ulong, double, decimal, and most structs. |
Errors: a volatile field of an unsupported type gives CS0677. Passing a volatile field by ref produces warning CS0420 ("a reference to a volatile field will not be treated as volatile"), which is a signal to use Volatile.Read/Write instead.
Usage notes
volatileguarantees that other threads see the latest value of that field and that reads and writes around it are not reordered across it in the forbidden directions. It does not guarantee atomicity of read-modify-write operations:_count++on a volatileintstill loses updates.- Typical correct uses: a stop/cancel flag, a "ready" flag that publishes data written earlier, and double-checked locking where the published object is read through a volatile field.
lockandInterlockedalready include the needed barriers, so you do not needvolatileon fields that are only touched inside a lock.- For
longanddouble, useVolatile.Read(ref x)andVolatile.Write(ref x, v), orInterlocked.Read, since the field modifier is not allowed. - On x86 and x64 many ordering problems are masked by the hardware, so a missing
volatilecan work on a laptop and fail on an ARM server. Do not rely on tests passing. - For a cooperative stop signal,
CancellationTokenis usually better than a hand-written volatile flag, and it composes with async code. volatilehas a small cost (it blocks some JIT optimizations), so do not scatter it "just in case".