Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions docs/csharp/language-reference/keywords/volatile.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
description: "volatile - C# Reference"
title: "volatile keyword"
ms.date: 01/22/2026
ms.date: 11/01/2026
f1_keywords:
- "volatile_CSharpKeyword"
- "volatile"
Expand Down Expand Up @@ -54,7 +54,14 @@ The following example demonstrates how an auxiliary or worker thread can be crea

:::code language="csharp" source="./snippets/volatile.cs" id="Volatile":::

When you add the `volatile` modifier to the declaration of `_shouldStop`, you always get the same results (similar to the excerpt shown in the preceding code). However, without that modifier on the `_shouldStop` member, the behavior is unpredictable. The `DoWork` method might optimize the member access, resulting in reading stale data. Because of the nature of multithreaded programming, the number of stale reads is unpredictable. Different runs of the program produce somewhat different results.
When you declare `_shouldStop` as `volatile`, the compiler and runtime ensure that its value is read on each loop iteration, rather than reusing a previously read value, and that the required memory ordering constraints are respected.

Without the `volatile` modifier, the runtime is allowed to optimize the loop by hoisting the read of `_shouldStop` outside the `while` loop. If hoisted, the loop never re-checks the field value in memory, causing the worker thread to loop indefinitely even after the main thread sets `_shouldStop` to `true`.

> [!NOTE]
> The behavior without the `volatile` modifier is non-deterministic. Depending on runtime conditions, hardware architecture, and compiler or runtime optimizations, different runs or environments might produce varying outcomes.
Comment thread
jkotas marked this conversation as resolved.
Resolved
>
> Prefer using <xref:System.Threading.CancellationTokenSource> and <xref:System.Threading.CancellationToken> for thread cancellation rather than manual volatile boolean flags.
## C# language specification

Expand Down
Loading