Monitor.Wait can throw ThreadInterruptedException without reacquiring the lock

Aperta
#137,329 5 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
42/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
csharp
Ambito
backend

Direzione di ricerca

Start with Condition.Wait and Lock.Reenter in System.Private.CoreLib, as linked in the issue, then trace the Monitor.Wait path introduced around #118371. Reproduce with the provided C# program on .NET 11 and inspect nearby synchronization tests for coverage. Done means Monitor.Wait throws ThreadInterruptedException only after reacquiring the lock at its prior recursion count, without leaving the waiter list inconsistent.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

area-System.Threading untriaged
Description

On .NET 11, a Thread.Interrupt that arrives while Monitor.Wait is blocked reacquiring the lock makes Monitor.Wait throw ThreadInterruptedException without holding the lock. The enclosing lock statement then throws SynchronizationLockException from Monitor.Exit, which replaces the original exception.

The program below gets there with two interrupts: the first ends the wait, the second arrives during the reacquisition.

Reproduction Steps

Save as repro.cs and run dotnet run repro.cs:

object gate = new();
bool ready = false;

Thread worker = new(() =>
{
    lock (gate)
    {
        Volatile.Write(ref ready, true);

        try
        {
            Monitor.Wait(gate);
        }
        catch (ThreadInterruptedException)
        {
            Console.WriteLine($"Lock held after Monitor.Wait threw: {Monitor.IsEntered(gate)}");
        }
    }
});

worker.Start();
SpinWait.SpinUntil(() => Volatile.Read(ref ready));

// Entered once the worker is waiting.
lock (gate)
{
    // Ends the wait: the worker now blocks to reacquire the lock.
    worker.Interrupt();
    Thread.Sleep(100);

    // Interrupts the reacquisition.
    worker.Interrupt();
    Thread.Sleep(100);
}

worker.Join();
Expected behavior

A thread that enters Monitor.Wait holding the lock reacquires it, with its previous recursion count, before a ThreadInterruptedException reaches the caller. The program prints the following and exits normally, as it does on .NET 10:

Lock held after Monitor.Wait threw: True
Actual behavior
Lock held after Monitor.Wait threw: False
Unhandled exception. System.Threading.SynchronizationLockException: The calling thread does not hold the lock.
   at System.Threading.Lock.Exit()
   at System.Threading.Monitor.Exit(Object obj)
   at Program.<>c__DisplayClass0_0.<<Main>$>b__0() in repro.cs:line 18

The ThreadInterruptedException caught in the worker has this stack trace:

   at System.Threading.Thread.CheckForPendingInterrupt()
   at System.Threading.WaitHandle.WaitForMultipleObjectsIgnoringSyncContext(IntPtr* pHandles, Int32 numHandles, Boolean waitAll, Int32 millisecondsTimeout, Boolean useTrivialWaits)
   at System.Threading.WaitHandle.WaitOneNoCheck(Int32 millisecondsTimeout, Boolean useTrivialWaits, Object associatedObject, WaitHandleWaitSourceMap waitSource)
   at System.Threading.Lock.TryEnterSlow(Int32 timeoutMs, Int32 currentThreadId)
   at System.Threading.Lock.Enter()
   at System.Threading.Condition.Wait(Int32 millisecondsTimeout, Object associatedObjectForMonitorWait)
Regression?

Yes. The program behaves as expected on .NET 10.0.15 and fails every time on .NET 11.0.0.

Known Workarounds

None confirmed.

Configuration
  • .NET 11.0.0, CoreCLR
  • Windows 11 x64 and Linux x64
Other information

Condition.Wait reacquires the lock in its finally block through Lock.Reenter, which calls Enter(), an interruptible wait:

https://github.com/dotnet/runtime/blob/b44a866c6e25582a0142c8a6e967bb04545ffa15/src/libraries/System.Private.CoreLib/src/System/Threading/Condition.cs#L167

https://github.com/dotnet/runtime/blob/b44a866c6e25582a0142c8a6e967bb04545ffa15/src/libraries/System.Private.CoreLib/src/System/Threading/Lock.cs#L252

When Reenter throws, the rest of that finally block, which removes the waiter from the list, does not run either.

CoreCLR has used this code for Monitor since #118371.

Lingua principale
C#
Stelle
18.4k
Fork
5.8k
Merge medio
2g 19h
PR unite (30g)
590

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di dotnet/runtime

Tutte le issue di dotnet/runtime

Issue simili

Altre issue su C#

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.