Monitor.Wait can throw ThreadInterruptedException without reacquiring the lock

Đang mở
#137,329 5 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
42/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
csharp
Lĩnh vực
backend

Hướng nghiên cứu

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.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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.

Ngôn ngữ chính
C#
Star
18.4k
Fork
5.8k
Merge trung bình
2 ngày 19 giờ
Pull request đã merge (30 ngày)
590

Chuẩn bị môi trường

Mở trong Codespaces

Khởi chạy dev container của dự án ngay trên trình duyệt, bằng tài khoản GitHub của bạn.

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của dotnet/runtime

Tất cả issue của dotnet/runtime

Issue tương tự

Thêm issue về C#

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.