Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

volatile: practical reference

volatile: practical reference: volatile gives individual field reads and writes appropriate cross-thread visibility.

Version: C# language; verified against C# 14 reference

Syntax

volatile /* grammar-specific form */

volatile gives individual field reads and writes appropriate cross-thread visibility.

Use it for simple flags when no atomic compound operation is needed.

It does not make increment or a multi-field invariant atomic; prefer Volatile or Interlocked for explicit protocols.

Only certain field types are allowed, and the complete protocol still needs deliberate ordering.

The complete program actually uses volatile; its exact expected stdout is 3.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

Console.WriteLine(new State().Read()); sealed class State { private volatile int value = 3; public int Read() => value; }

Result

3

The complete program actually uses `volatile`; its exact expected stdout is `3`.

Sources