c#マルチスレッドプログラミングにおけるAutoResetEventとManualResetEvent

2254 ワード

Javaに等しいwait,notify,notifyAllの存在として,AutoResetEventとManualResetEventはそれぞれnotifyとnotifyAllの機能を実現しており,以下のコードでは実現原理を簡単に説明し,この過程を示した.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ThreadTest
{
    class Program
    {
        //                  
        private void Test()
        {
            ManualResetEvent manualResetEvent = new ManualResetEvent(false);
            AutoResetEvent autoResetEvent = new AutoResetEvent(false);
            //        ParameterizedThreadStart  ,  Start     。
            new Thread(new ParameterizedThreadStart(MyThreadHandler)).Start(new ParamStruct("Thread1", manualResetEvent));
            new Thread(new ParameterizedThreadStart(MyThreadHandler)).Start(new ParamStruct("Thread2", manualResetEvent));
            new Thread(new ParameterizedThreadStart(MyThreadHandler)).Start(new ParamStruct("Thread3", autoResetEvent));
            new Thread(new ParameterizedThreadStart(MyThreadHandler)).Start(new ParamStruct("Thread4", autoResetEvent));
            Thread.Sleep(1000);
            //manualResetEvent Set   ,          ,     wait       ,  NotifyAll
            manualResetEvent.Set();
            //autoResetEvent Set   ,       wait             Reset,     ,  NotifyOne
            autoResetEvent.Set();
            Thread.Sleep(1000);
            autoResetEvent.Set();
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            new Program().Test();
        }
        private void MyThreadHandler(object obj)
        {
            if (obj is ParamStruct paramStruct)
            {
                Console.WriteLine(paramStruct.threadName);
                paramStruct.resetEvent.WaitOne();
                Console.WriteLine(paramStruct.threadName + " finished on " + DateTime.Now);
            }
        }
    }
    class ParamStruct
    {
        public string threadName;
        public EventWaitHandle resetEvent;
        public ParamStruct(string threadName, EventWaitHandle resetEvent)
        {
            this.threadName = threadName;
            this.resetEvent = resetEvent;
        }
    }
}