C#:Monitor.Pulse() 不起作用

C#: Monitor.Pulse() doesn't work

我遇到了一个问题,我将其减少到这个最小值 test-case,但我仍然不明白为什么它不能正常工作。这里的代码很简单:parent 线程获取一个锁,然后启动一个 child,接下来通过启动 await 来释放锁。然后被锁定在同一个锁上的 child 线程继续,释放 parent,接下来休眠五秒钟。

using System.Threading;
using System;
using System.IO;
using System.Diagnostics;

namespace Test
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Object waitForThrToStart = new Object();
            lock (waitForThrToStart)
            {
                new Thread(() =>
                {
                    lock (waitForThrToStart)
                    {
                        Debug.WriteLine("2. Child: free the parent");
                        Monitor.Pulse(waitForThrToStart);
                        Debug.WriteLine("3. Child: pulsed ☺ Now sleep");
                        Thread.Sleep(5000);
                        Debug.WriteLine("5. Child: time out");
                    }
                }).Start();
                Debug.WriteLine("1. Parent: waiting");
                Monitor.Wait(waitForThrToStart);
                Debug.WriteLine("4. Parent: awoke, exiting now");
            }
        }
    }
}

很好,只是……它不起作用。 parent 仅在五秒后释放,当 child 退出时,您可能会在输出中看到它:

1. Parent: waiting
2. Child: free the parent
3. Child: pulsed ☺ Now sleep
5. Child: time out
4. Parent: awoke, exiting now

我什至尝试使用 Monitor.PulseAll(),但没有任何改变。我还认为,也许出于某种奇怪的原因,child 得到了 Object 的副本,因此它们在不同的变量上工作。但是我通过在 parent 中设置一个 Sleep() 调用来反驳它 — child 肯定在等待锁。

这是什么,这是一个错误吗?有什么解决方法吗?

您在 child 中对监视器进行脉动,但您也已将其锁定。 Wait 只会 return 一旦你释放了 child 线程中的锁,此时它需要在 returning 之前重新获取锁。