Goodspeed

导航

线程同步中使用信号量AutoResetEvent

using System;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            p.Do();
            p.Signal();
        }

        AutoResetEvent autoResetEvent = new AutoResetEvent(false); //false代表默认中阻塞状态

        void Do()
        {
            var worker = new Thread(() =>
            {
                Console.WriteLine("Start worker");
                Console.WriteLine("wait");
                autoResetEvent.WaitOne(); //等待信号
                Console.WriteLine("do");
            });
            worker.Start();
        }

        void Signal()
        {
            Console.WriteLine("Sent signal");
            Console.ReadKey();
            autoResetEvent.Set(); //发送信号
            Console.ReadKey();
        }
    }
}

ManualResetEvent需要手动设定阻塞状态设置为false

posted on 2014-11-02 09:54  Goodspeed  阅读(359)  评论(0编辑  收藏  举报