ManualResetEventSlim(手动重置事件)-【玩迪士尼的游乐项目很无奈,一波波等(管理人员手动开关门,大家在门口排队一波波进入)】

  ManualResetEventSlim的整个工作方法有点像人群通过大门,AutoResetEvent事件像一个旋转门,一次只允许一人通过。ManualResetEventSlim是ManualResetEvent的混合版本,一直保持大门敞开直到手动调用Reset方法。当调用_mainEvent.Set时,相当于打开了大门从而允许准备好的线程接收信号并继续工作。然而线程3还处于睡眠状态,没有赶上时间。当调用_mainEvent.Reset相当于关闭了大门。最后一个线程已经准备好要执行,但是不得不等待下一个信号。

     static void Main(string[] args)
        {
            var t1 = new Thread(() => TravelThroughGates("Thread 1", 5));
            var t2 = new Thread(() => TravelThroughGates("Thread 2", 6));
            var t3 = new Thread(() => TravelThroughGates("Thread 3", 12));
            t1.Start();
            t2.Start();
            t3.Start();
            Thread.Sleep(TimeSpan.FromSeconds(6));
            Console.WriteLine("开门!");
            _mainEvent.Set();
            Thread.Sleep(TimeSpan.FromSeconds(2));
            _mainEvent.Reset();
            Console.WriteLine("关门!");
            Thread.Sleep(TimeSpan.FromSeconds(10));
            Console.WriteLine("第二次开门!");
            _mainEvent.Set();
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Console.WriteLine("彻底关门!");
            _mainEvent.Reset();

            Console.ReadKey();
        }

        static void TravelThroughGates(string threadName, int seconds)
        {
            Console.WriteLine("{0} 歇着,挂起", threadName);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            Console.WriteLine("{0} 等待开门!", threadName);
            _mainEvent.Wait();
            Console.WriteLine("{0} 进门!", threadName);
        }

        static ManualResetEventSlim _mainEvent = new ManualResetEventSlim(false);

猜你喜欢

转载自www.cnblogs.com/gougou1981/p/12355669.html
今日推荐