2015-09-24

EventWaitHandle C# Example


using System;
using System.Threading;

namespace WaitEvent
{
        class MainClass
        {
                static EventWaitHandle waitEvent = new AutoResetEvent (false);
                public static void Main (string[] args)
                {
                        //this thread will wait the notification from waitEvent 
                        Thread wait = new Thread (WaitForPrintEvent);
                        wait.Start ();
                        Thread.Sleep (3000); 

                        //this thread will trigger the waitEvent
                        Thread print = new Thread (printMsg);
                        print.Start ();

                        print.Join ();
                        wait.Join ();
                }

                static void WaitForPrintEvent()
                {
                        //wait the notification from waitEvent to continue
                        waitEvent.WaitOne ();
                        Console.WriteLine ("after wait!");
                }

                static void printMsg()
                {
                        Console.WriteLine ("Print Message!");
                        //waitEvent is set,and will notify the guys that wait this event
                        waitEvent.Set ();
                }
        }
}



Reference 
C# Threading 

No comments: