Baza wiedzyCentrum egzaminacyjne
PLPolski
Wybierz język13

CKTIS / C#

volatile: odniesienie praktyczne

volatile: odniesienie praktyczne: volatile wymusza odpowiednią widoczność odczytów/zapisów pojedynczego pola między wątkami.

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

Składnia

volatile /* grammar-specific form */

volatile wymusza odpowiednią widoczność odczytów/zapisów pojedynczego pola między wątkami.

Stosuj do prostych flag, gdy nie potrzeba atomowej operacji złożonej.

Nie czyni increment ani invariantu wielu pól atomowym; preferuj Volatile/Interlocked dla jawności.

Dozwolone typy pól są ograniczone; kolejność całego protokołu nadal wymaga projektu.

Kompletny program rzeczywiście używa volatile; oczekiwany stdout to dokładnie 3.

Przykłady

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; }

Wynik

3

Kompletny program rzeczywiście używa `volatile`; oczekiwany stdout to dokładnie `3`.

Źródła