CKTIS / C#
System.Threading.Interlocked: referência prática
System.Threading.Interlocked: referência prática: Interlocked executa operações atómicas leitura-modificação-escrita em localizações suportadas.
Versão: .NET API; verified against .NET 10 reference surface
Sintaxe
System.Threading.Interlocked /* select a documented member or constructor */Interlocked executa operações atómicas leitura-modificação-escrita em localizações suportadas.
Usa-o para contadores, flags e compare-exchange simples sem um lock completo.
A atomicidade de uma operação não protege um invariante que abranja vários campos.
Increment pode dar a volta sem lançar; CompareExchange devolve o valor anterior.
O programa completo usa realmente System.Threading.Interlocked; o stdout exato esperado é 1.
Exemplos
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;
var value = 0;
Console.WriteLine(Interlocked.Increment(ref value));
Resultado
1
O programa completo usa realmente `System.Threading.Interlocked`; o stdout exato esperado é `1`.