Developer knowledge network · moderated exchange

UnreliableCode-Community

Community für Entwicklerforschung, Reverse Engineering und Codierung

Knowledge indexLive
4Categories
919Threads
2.8KBeiträge
Tutorial

The new System.Threading.Lock type in C# 13 and .NET 9: Lighter, faster synchronization [StackOverflow Architecture Guide]

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Vertreter: 103
Beitrittsdatum: Apr 2018
Beiträge: 40
Danke: 24
Vor 3 Wochen · Aug 2, 2026 2:54 PM
#1

How .NET 9 replaces object monitor locks with dedicated System.Threading.Lock:

Before C# 13, lock(new object()) compiled to Monitor.Enter() / Monitor.Exit(), requiring runtime sync block index allocations in the object header.

In .NET 9:

CSHARP
private readonly Lock _gate = new();

void ThreadSafeOperation()
{
    lock (_gate) // C# 13 emits _gate.EnterScope()!
    {
        // Critical Section
    }
}

Lock.EnterScope() returns a ref struct scope guard. Eliminates sync block table lookups and executes faster on multi-core CPUs!

cpp_concurrency_guru
C++ Standards Expert
MEMBER
Vertreter: 47
Beitrittsdatum: Feb 2018
Beiträge: 17
Danke: 75
Vor 3 Wochen · Aug 2, 2026 6:21 PM
#2

The Roslyn compiler automatically recognizes System.Threading.Lock and generates optimal EnterScope() calls instead of Monitor.Enter.

profiler_pat
Performance Hunter
MEMBER
Vertreter: 146
Beitrittsdatum: Aug 2019
Beiträge: 33
Danke: 31
Vor 3 Wochen · Aug 3, 2026 8:33 AM
#3

A great modernization of C#'s classic lock keyword.