Developer knowledge network ยท moderated exchange

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Knowledge indexLive
4Categories
919Threads
2.8KPosts
Tutorial

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

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Rep: 47
Join Date: Feb 2018
Posts: 17
Thanks: 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
Rep: 103
Join Date: Apr 2018
Posts: 40
Thanks: 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
Rep: 146
Join Date: Aug 2019
Posts: 33
Thanks: 31
1 months ago ยท Jul 4, 2026 1:58 AM
#3

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