是否有一种简单的方法可以检查是否有任何线程正在等待特定的ManualResetEvent 要设置的对象?在我看来,计算机必须以某种方式保持队列 暂停后续恢复的线程,所以我只是希望做明显的访问 这个清单(只是为了检查它是否为空)......但我找不到了 查看Microsoft相关的Threading / WaitHandle / Monitor帮助页面的方法。
测试代码如下。我只想更换丑陋的手表柜台。
using System;
using System.Threading;
namespace demo
{
class Program
{
static void Main()
{
var gate = new ManualResetEvent(false);
int uglyWaiters = 0; // I want to stop using this variable and instead use something built into ManualResetEvent
new Thread(() =>
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("a" + i);
uglyWaiters++;
gate.WaitOne();
uglyWaiters--;
Thread.Sleep(400);
}
}).Start();
new Thread(() =>
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine("b" + i);
uglyWaiters++;
gate.WaitOne();
uglyWaiters--;
Thread.Sleep(500);
}
}).Start();
for (int count = 0; count < 15; count++)
{
Console.WriteLine(uglyWaiters + " threads waiting at t=" + count*230 + "ms");
gate.Set(); Thread.Sleep(30); gate.Reset();
Thread.Sleep(200);
}
Console.ReadLine();
}
}
}