Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

Knowledge indexيعيش
4Categories
919Threads
2.8Kدعامات
Tutorial

High-Performance Interlocked Operations vs Locks in C#: When to use CompareExchange [StackOverflow Architecture Guide]

cpp_concurrency_guru
C++ Standards Expert
MEMBER
مندوب: 47
تاريخ الانضمام: Feb 2018
دعامات: 17
شكرًا: 75
1 months ago · Jul 3, 2026 9:41 AM
#1

Implementing lock-free updates using Interlocked.CompareExchange:

CSHARP
public static void UpdateMax(ref int target, int newValue)
{
    int current = target;
    while (newValue > current)
    {
        int previous = Interlocked.CompareExchange(ref target, newValue, current);
        if (previous == current) break; // Successful atomic update!
        current = previous;
    }
}

Executes with a single atomic hardware CMPXCHG instruction on x86, avoiding OS kernel thread suspension and context switches!

dotnet_runtime_architect
.NET Core Specialist
MEMBER
مندوب: 103
تاريخ الانضمام: Apr 2018
دعامات: 40
شكرًا: 24
1 months ago · Jul 3, 2026 1:31 PM
#2

Interlocked.CompareExchange loops (CAS loops) are the foundation of lock-free data structures in .NET.

profiler_pat
Performance Hunter
MEMBER
مندوب: 146
تاريخ الانضمام: Aug 2019
دعامات: 33
شكرًا: 31
1 months ago · Jul 4, 2026 1:58 AM
#3

Much faster than lock(obj) when contention is short and infrequent.