Sunday, 24 July 2011

Optimizing wait in MultiThreading Environment – C#


While working in Multithreading environment the primary thread has to wait until it’s secondary thread to complete their execution. So in this case most of the time we use Thread.Sleep() and that is a bad practice because it blocks the primary thread for a time that might be less or exceeds than the completion time of secondary thread.  You can optimize the waiting time in multithreading by using System.Threading.AutoResetEvent class.
To achieve this we’ll utilize the WaitOne() method of AutoResetEvent class. it’ll wait until the it gets notified from secondary thread for completion and This I think should be the optimized way for wait here.
Let see the example:
using System;
using System.Threading;
namespace Threads_CSHandler_AutoResetEvent
{
    class Program
    {
        //Declare the wait handler
        private static AutoResetEvent waitHandle = new AutoResetEvent(false);

        static void Main(string[] args)
        {
            Console.WriteLine("Main() running on thread {0}", Thread.CurrentThread.ManagedThreadId);

            Program p = new Program();
            Thread t = new Thread(new ThreadStart(p.PrintNumbers));
            t.Start();
            //Wait untill get notified
            waitHandle.WaitOne();
            Console.WriteLine("\nSecondary thread is done!");
            Console.Read();
        }

        public void PrintNumbers()
        {
            Console.WriteLine(" ");
            Console.WriteLine("Executing Thread {0}", Thread.CurrentThread.ManagedThreadId);
            for (int i = 1; i <= 10; i++)
            {
                //Just to consume some time in operation
                Thread.Sleep(100);
                Console.Write(i + " ");
            }
            //Tell other other thread that we're done here
            waitHandle.Set();
        }
    }
}

Output:

Fun while it’snt done !!