Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

Knowledge indexيعيش
4Categories
919Threads
2.8Kدعامات
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
مندوب: 103
تاريخ الانضمام: Apr 2018
دعامات: 40
شكرًا: 24
3 weeks ago · 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
مندوب: 47
تاريخ الانضمام: Feb 2018
دعامات: 17
شكرًا: 75
3 weeks ago · 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
مندوب: 146
تاريخ الانضمام: Aug 2019
دعامات: 33
شكرًا: 31
3 weeks ago · Aug 3, 2026 8:33 AM
#3

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