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

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
Rozpustnik: 103
Data dołączenia: Apr 2018
Posty: 40
Dzięki: 24
3 tygodnie temu · 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
Rozpustnik: 47
Data dołączenia: Feb 2018
Posty: 17
Dzięki: 75
3 tygodnie temu · 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
Rozpustnik: 146
Data dołączenia: Aug 2019
Posty: 33
Dzięki: 31
3 tygodnie temu · Aug 3, 2026 8:33 AM
#3

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