Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.Threading.Interlocked: practical reference

System.Threading.Interlocked: practical reference: Interlocked performs atomic read-modify-write operations on supported memory locations.

Version: .NET API; verified against .NET 10 reference surface

Syntax

System.Threading.Interlocked /* select a documented member or constructor */

Interlocked performs atomic read-modify-write operations on supported memory locations.

Use it for simple counters, flags, and compare-exchange without a full lock.

Atomicity of one operation does not protect an invariant spanning several fields.

Increment can wrap without throwing; CompareExchange returns the previous value.

The complete program actually uses System.Threading.Interlocked; its exact expected stdout is 1.

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;

var value = 0;
Console.WriteLine(Interlocked.Increment(ref value));

Result

1

The complete program actually uses `System.Threading.Interlocked`; its exact expected stdout is `1`.

Sources