事件锁-AutoResetEvent介绍及使用场景

AutoResetEvent 允许线程通过发信号互相通信。通常,此通信涉及线程需要独占访问的资源。

线程通过调用 AutoResetEvent 上的 WaitOne 来等待信号。如果 AutoResetEvent 处于非终止状态,则该线程阻塞,并等待当前控制资源的线程
通过调用 Set 发出资源可用的信号。

调用 Set 向 AutoResetEvent 发信号以释放等待线程。AutoResetEvent 将保持终止状态,直到一个正在等待的线程被释放,然后自动返回非终止状态。如果没有任何线程在等待,则状态将无限期地保持为终止状态。

等待的才会执行。如果不发的话,WaitOne后面的程序就永远不会执行。

下面例子有三个线程,使用事件锁来实现同步执行:

static void Main(string[] args)
        {
            var t1ResetEvent = new AutoResetEvent(false);
            var t2ResetEvent = new AutoResetEvent(false);
            var t3ResetEvent = new AutoResetEvent(false);
            Task t1 = new Task(() =>
            {
                while (true)
                {
                    if (t1ResetEvent.WaitOne())
                    {
                        Console.WriteLine("t1");
                        Thread.Sleep(500);
                        t2ResetEvent.Set();
                    }
                }
            });
            Task t2 = new Task(() =>
            {
                while (true)
                {
                    if (t2ResetEvent.WaitOne())
                    {
                        Console.WriteLine("t2");
                        Thread.Sleep(500);
                        t3ResetEvent.Set();
                    }
                }
            });
            Task t3 = new Task(() =>
            {
                while (true)
                {
                    if (t3ResetEvent.WaitOne())
                    {
                        Console.WriteLine("t3");
                        Thread.Sleep(500);
                    }
                }
            });
            t1.Start();
            t2.Start();
            t3.Start();
            t1ResetEvent.Set();
            Thread.Sleep(3000);
            t1ResetEvent.Set();
            Thread.Sleep(3000);
            t1ResetEvent.Set();
            Console.ReadKey();
        }

//结果 t1、t2、t3、t1、t2、t3、t1、t2、t3
原文地址:https://www.cnblogs.com/fanfan-90/p/12006822.html