Developer knowledge network ยท moderated exchange

Komunitas Kode Tidak Dapat Diandalkan

Riset Pengembang, Rekayasa Terbalik & Komunitas Pengkodean

Knowledge indexHidup
4Categories
919Threads
2.8KPostingan
Tutorial

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

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Reputasi: 47
Tanggal Bergabung: Feb 2018
Postingan: 17
Terima kasih: 75
1 bulan yang lalu ยท 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
Reputasi: 103
Tanggal Bergabung: Apr 2018
Postingan: 40
Terima kasih: 24
1 bulan yang lalu ยท 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
Reputasi: 146
Tanggal Bergabung: Aug 2019
Postingan: 33
Terima kasih: 31
1 bulan yang lalu ยท Jul 4, 2026 1:58 AM
#3

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