skip to content

In C# 13 and later, what changes when a lock statement's target is a System.Threading.Lock rather than a plain object?

level: middleimportance: should knowfreq 28%

answer

  1. a dedicated type from .NET 9
  2. the static type decides the lowering
  3. EnterScope returns a ref struct
  4. converting to object brings Monitor back

basics

~20 s

When the target's compile-time type is System.Threading.Lock (.NET 9), C# 13 lowers lock to using (x.EnterScope()) instead of Monitor calls. Converting that Lock to object brings back Monitor locking, which the compiler flags as warning CS9216.

solid answer

~40 s

`System.Threading.Lock` is a sealed class added in .NET 9, and from C# 13 the compiler recognises it: `lock (_gate)` on a field of that type becomes `using (_gate.EnterScope()) { ... }`, where `EnterScope` returns a `Lock.Scope` ref struct whose `Dispose` exits the lock. The behaviour you rely on stays: one thread at a time, re-entrant for the owner, released on exceptions, and `await` inside the body is still error CS1996. What changes is the mechanism, and it is chosen by the **compile-time type**. `object o = _gate; lock (o)` takes a `Monitor` lock on the same instance, and a `Monitor` lock and a `Lock` do not exclude each other, so the compiler warns with CS9216. Under LangVersion 12 a `lock` on a `Lock` is error CS9202. `Lock` has no counterpart of `Monitor.Wait` or `Monitor.Pulse`.

code

csharp · 25 lines
csharp
using System.Threading;

Lock gate = new();
object asObject = gate;

using var held = new ManualResetEventSlim();
using var done = new ManualResetEventSlim();

var owner = new Thread(() =>
{
    lock (gate)                 // Lock.EnterScope()
    {
        held.Set();
        done.Wait();
    }
});
owner.Start();
held.Wait();

bool entered = Monitor.TryEnter(asObject, 100);   // what lock (asObject) would do
Console.WriteLine($"Monitor entered while Lock held: {entered}");
Console.WriteLine($"Lock.TryEnter from main thread: {gate.TryEnter(100)}");
if (entered) Monitor.Exit(asObject);
done.Set();
owner.Join();

go deeper

for a junior

Recall that .NET 9 added a Lock type, that you declare the lock field as Lock instead of object, and that the lock statement itself is written the same way.

for a middle

Explain the EnterScope lowering, why the compile-time type picks it, and what CS9216 and CS9202 tell you.

for a senior

Show the failure mode: a Lock that escapes as object gets Monitor locking, which does not exclude Lock holders, so the class loses mutual exclusion with only a warning.

for a principal

Weigh a migration rule for a codebase: adopt Lock where the target framework allows, make CS9216 an error, and leave Monitor in place where Wait and Pulse are used.

## The type and the new lowering Before .NET 9, the only lock the C# `lock` statement knew was `System.Threading.Monitor`: any reference-type object could be a lock target, and the compiler expanded the statement into `Monitor.Enter` in a `try` and `Monitor.Exit` in a `finally`. **.NET 9 added `System.Threading.Lock`**, a sealed class whose only job is mutual exclusion, and **C# 13 taught the `lock` statement to recognise it**. When the compiler knows the target is a `Lock`, Microsoft's language reference says the statement is precisely equivalent to: ```csharp using (x.EnterScope()) { // the body of the lock statement } ``` `EnterScope()` acquires the lock and returns a **`Lock.Scope`**, a `ref struct` whose `Dispose()` exits it; the `using` statement guarantees the dispose runs when the body throws. Migrating a class is a one-word change: ```csharp private readonly Lock _gate = new(); // was: private readonly object _gate = new(); ``` Every `lock (_gate)` in the class picks up the new lowering with no other edit, and Microsoft's guidance recommends a dedicated `Lock` instance on .NET 9 and later for best performance. ## The compile-time type decides The compiler chooses the lowering from the **static type of the expression** in the parentheses, not from the object it refers to at run time: | Target expression | Generated code | Diagnostic | |---|---|---| | a field or local declared as `Lock` | `using (x.EnterScope())` | none | | the same instance through an `object` variable | `Monitor.Enter` / `Monitor.Exit` | warning CS9216 at the conversion | | a `Lock` with LangVersion 12 | not compiled | error CS9202 | | any other reference type | `Monitor.Enter` / `Monitor.Exit` | none | The CS9216 text, from the compiler: "A value of type 'System.Threading.Lock' converted to a different type will use likely unintended monitor-based locking in 'lock' statement." The CS9202 text under LangVersion 12: "Feature 'Lock object' is not available in C# 12.0. Please use language version 13.0 or greater." ## Monitor and Lock do not see each other The warning matters because the two mechanisms are **separate locks that happen to live on one object**. The example on this page runs a thread that holds `lock (gate)` through the `Lock` type, then has the main thread call `Monitor.TryEnter` on the same instance through an `object` reference: `Monitor.TryEnter` succeeds while the `Lock` is held, and only `gate.TryEnter` correctly reports that it is taken. A class where one method locks the `Lock` field and another locks it after a conversion to `object` (passing it to a helper that takes `object`, or adding it to a `List<object>`) therefore has **no mutual exclusion between those two methods**, and only a warning to tell you. A generic method that does `lock (t)` on a `T` parameter also gets `Monitor` when called with a `Lock`, and in that case the compiler reports nothing, because no conversion happens. ## What stays the same - **Exclusion and re-entrancy.** One thread at a time; the owner can enter again, and the `Lock` source says it should exit as many times as it entered. - **Exception safety.** The `using` replaces the `try`/`finally`, so a throwing body still releases the lock. - **No `await` in the body.** A `lock` on a `Lock` is still a thread-owned lock, so `await` inside it remains error CS1996; asynchronous code still needs `SemaphoreSlim`. - **Reference identity.** The lock is still per instance: two `new Lock()` objects are two locks. ## What the Lock type does not offer `Lock`'s public surface is `Enter`, `TryEnter` (with and without a timeout), `Exit`, `EnterScope` and `IsHeldByCurrentThread`. There is **no counterpart of `Monitor.Wait`, `Monitor.Pulse` or `Monitor.PulseAll`**, so a class that uses a lock object as a condition variable keeps an `object` and `Monitor`. ## Migrating a class safely 1. Confirm the project targets .NET 9 or later and compiles as C# 13 or later; otherwise the type is missing or the `lock` is CS9202. 2. Change the field's declared type to `Lock`, keeping it `private readonly`. 3. Build and treat **CS9216 as an error**: each hit is a place where the instance escapes as another type and would silently fall back to `Monitor`. 4. Search for `Monitor.` calls on the field; `Wait` and `Pulse` users cannot migrate. 5. Keep the field private, so no outside code can lock it through another type. Projects on target frameworks older than .NET 9 do not have this type at all; the release clause above tells you whether your build has it.

  • Why is CS9216 a warning worth treating as an error when migrating to Lock?
    Each hit marks a place where a `Lock` is converted to another type, and a `lock` through that type compiles to `Monitor`. A `Monitor` lock and a `Lock` on the same instance do not exclude each other, so code that locks both ways loses mutual exclusion silently. Making the warning an error stops those conversions from compiling; a generic `lock (t)` on a type parameter is not caught, because no conversion happens.
  • Can a class that coordinates threads with Monitor.Wait and Monitor.Pulse switch its lock object to Lock?
    Not directly. `Lock` exposes `Enter`, `TryEnter`, `Exit`, `EnterScope` and `IsHeldByCurrentThread`, and has no wait or pulse methods. That class keeps a plain `object` with `Monitor`, or is redesigned around another signalling primitive.

  • Declaring the field as Lock means await is now allowed inside lock.
  • System.Threading.Lock is a ref struct, so it cannot be stored in a field.
  • Locking a Lock through an object variable still calls EnterScope.
  • A Monitor lock and a Lock on the same instance block each other.
  • A lock statement on a Lock compiles under any LangVersion once the target is .NET 9.

Assumes C# 14 on .NET 10; System.Threading.Lock shipped in .NET 9 and the lock statement recognises it from C# 13 (LangVersion 12 reports CS9202).