AutoResetEvent的简单理解

努力的成为一名牛逼的女程序员!


这段时间有接触到AutoResetEvent,在自己简单理解之后,做了个小demo,介绍下基本用法,欢迎大家指正!

说明:

  1. 网上很多都是用了两个AutoResetEvent对象来模拟,我这里用一个。
  2. 每次交换用10秒钟来间隔,以便看清过程
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AutoResetEventTest
{
    class Program
    {
        private static AutoResetEvent autoResetEvent = new AutoResetEvent(false);

        static void Main(string[] args)
        {
            var playtime = 10;
            Console.WriteLine("两个游戏柄坏了其中一只,A和B只能各玩一会...");
            var t = new Thread((() => Process(playtime)));
            t.Start();
            Console.WriteLine("B先玩,A开始等待...");
            autoResetEvent.WaitOne();

            Console.WriteLine("A获得了游戏柄");
            Console.WriteLine("A开始第二局,B开始等待...");
            Thread.Sleep(TimeSpan.FromSeconds(playtime));
            autoResetEvent.Set();
            autoResetEvent.WaitOne();
            Console.WriteLine("A获得了游戏柄");
            Console.WriteLine("A关掉电源,游戏结束...");
            Console.ReadKey();
        }

        static void Process(int seconds)
        {
            Console.WriteLine("B开始玩第一局...");
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            Console.WriteLine("第一局结束,B把手柄给A");
            autoResetEvent.Set();
            autoResetEvent.WaitOne();

            Console.WriteLine("第二局结束,A把手柄给B");
            Console.WriteLine("B开始玩第三局...");
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            Console.WriteLine("第三局结束,B把手柄给A");
            autoResetEvent.Set();
        }
    }
}

附上结果图:
AutoResetEvent的简单理解