Synchronize the Execution of Multiple Threads Using an Event - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Synchronize

Description

Synchronize the Execution of Multiple Threads Using an Event

Demo Code


using System;//from w  w  w.j  a  v  a 2 s . co  m
using System.Threading;

class MainClass
    {
        static bool terminate = false;
        private static void TraceMsg(string msg)
        {
            Console.WriteLine("[{0,3}] - {1} : {2}",
                Thread.CurrentThread.ManagedThreadId,
                DateTime.Now.ToString("HH:mm:ss.ffff"), msg);
        }
        private static void DisplayMessage()
        {
            EventWaitHandle eventHandle = EventWaitHandle.OpenExisting("EventExample");

            TraceMsg("DisplayMessage Started.");

            while (!terminate)
            {
                if (eventHandle.WaitOne(2000, true))
                {
                    TraceMsg("EventWaitHandle In Signaled State.");
                }
                else
                {
                    TraceMsg("WaitOne Timed Out -- " + "EventWaitHandle In Unsignaled State.");
                }
                Thread.Sleep(2000);
            }

            TraceMsg("Thread Terminating.");
        }

        public static void Main()
        {
            using (EventWaitHandle eventWaitHandle = new EventWaitHandle(true, EventResetMode.ManualReset,"EventExample"))
            {
                TraceMsg("Starting DisplayMessageThread.");
                Thread trd = new Thread(DisplayMessage);
                trd.Start();
                for (int count = 0; count < 3; count++)
                {
                    if (eventWaitHandle.WaitOne(0, true))
                    {
                        TraceMsg("Switching Event To UnSignaled State.");
                        eventWaitHandle.Reset();
                    }
                    else
                    {
                        TraceMsg("Switching Event To Signaled State.");
                        eventWaitHandle.Set();
                    }
                }
                terminate = true;
                eventWaitHandle.Set();
                trd.Join(5000);
            }
        }
    }

Result


Related Tutorials