假设一个使用场景:
1. 有一台仪器,需要预热后才能使用;
2. 需要使用线程操作这台仪器;
static bool isReady = false; public static void Test1() { Thread th = new Thread(() => { while (!isReady) ; //不断执行此语句 Console.WriteLine("开始工作"); }); th.Start(); Console.WriteLine("按任意键继续..."); Console.ReadKey(); isReady = true; Console.ReadKey(); }
使用ManualResetEvent后:
//注意到这里设置为false, static ManualResetEvent manual = new ManualResetEvent(false); public static void Test1() { Thread th = new Thread(() => { manual.WaitOne(); Console.WriteLine("开始工作"); }); th.Start(); Console.WriteLine("按任意键继续..."); Console.ReadKey(); manual.Set(); Console.ReadKey(); }
性能差距居然如此巨大!
再看一下,改为:
static ManualResetEvent manual = new ManualResetEvent(true);
manual.WaitOne(); //这句不再进行阻塞了
也就是说:
static ManualResetEvent manual = new ManualResetEvent(false); //代表一开始要进行阻塞,相当于 isReady = false
manual.Set(); //代表将false改为true,相当于isReady = false
manual.WaitOne(); //
原文:https://www.cnblogs.com/pylblog/p/12887494.html