Developer knowledge network · moderated exchange

Сообщество UnreliableCode

Сообщество разработчиков, обратного проектирования и кодирования

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 недель назад · 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 недель назад · 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 недель назад · Aug 3, 2026 8:33 AM
#3

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