所以我使用 Monitor.Wait 进行了一个简单的测试,超时设置为三秒。据我了解,当时间到期时,会向监视器发送一个虚拟脉冲以释放等待。然而,在我的测试中,这似乎从未发生过。有人可以解释发生了什么。这是我的测试代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace BlockingMethodFoo
{
class Program
{
static void Main(string[] args)
{
WaitFoo foo = new WaitFoo();
foo.StartMethod();
Console.WriteLine("Done. Press enter");
Console.ReadLine();
}
}
public class WaitFoo
{
private object _waitObj = new object();
private string _message = string.Empty;
public void StartMethod()
{
Thread waitThread = new Thread(new ThreadStart(new Action(() => { WaitMethod(); })));
_message = string.Empty;
Console.WriteLine("Starting wait");
_message = "Time Out";
lock (_waitObj)
{
waitThread.Start();
Monitor.Wait(_waitObj, TimeSpan.FromSeconds(3));
}
Console.WriteLine(_message);
}
private void WaitMethod()
{
lock (_waitObj)
{
_message = Console.ReadLine();
Monitor.Pulse(_waitObj);
}
}
}
}