Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
Tutorial

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

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Rozpustnik: 47
Data dołączenia: Feb 2018
Posty: 17
Dzięki: 75
1 miesięcy temu · 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
Rozpustnik: 103
Data dołączenia: Apr 2018
Posty: 40
Dzięki: 24
1 miesięcy temu · 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
Rozpustnik: 146
Data dołączenia: Aug 2019
Posty: 33
Dzięki: 31
1 miesięcy temu · Jul 4, 2026 1:58 AM
#3

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