線程同步中使用信號量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須要手動設定阻塞狀態設置爲falsespa

相關文章
相關標籤/搜索