先说结论:
AutoResetEvent threadEvent = new AutoResetEvent(false);
传入true相当于在传入false的基础上使用了一次Set();
即threadEvent.Set();
那么第一次碰到的WaitOne()就会直接跳过;
下面2张图可以很好说明设置为true和false的区别
namespace LearnCsharp
{
internal class Program
{
static void Main(string[] args)
{
StartLearnAutoResetEvent();
}
}
class Work
{
int cnt = 0;
public void run()
{
while(true)
{
cnt++;
LearnAutoResetEvent.threadEvent.WaitOne();
Console.WriteLine($"{Thread.CurrentThread.Name} 工作完毕 : 第{cnt}次等待");
}
}
}
public class LearnAutoResetEvent
{
public static AutoResetEvent threadEvent = new AutoResetEvent(false);
public void start()
{
Work[] work = new Work[3];
work[0] = new Work();
work[1] = new Work();
work[2] = new Work();
Thread thread3 = new Thread(work[2].run);
Thread thread = new Thread(work[0].run);
Thread thread2 = new Thread(work[1].run);
thread.Name = "thread1";
thread2.Name = "thread2";
thread3.Name = "thread3";
thread2.Start();
thread.Start();
thread3.Start();
Thread.Sleep(2000);
for (int i=0;i<10;i++)
{
Console.WriteLine($"第{i}次唤醒");
threadEvent.Set();
Thread.Sleep(2000);
}
}
}
}
代码设置为true和false的运行结果分别如下:
true
false
可以发现设置为true, 在唤醒之前, 就自动跳过WaitOne自动完成了任务.
参考视频:https://www.bilibili.com/video/BV1uz4y1v7ZS