Optimizing Wait in MultiThreading Environment - C#



In a Multithreading environment the primary thread often must wait until its secondary thread to completes its execution. So in that case we often use Thread.Sleep() but that is a bad practice because it blocks the primary thread for a time that might be less or greater than the completion time of the secondary thread (it is imprecise). You can optimize the waiting time in multithreading using the System.Threading.AutoResetEvent class.

To achieve this we'll utilize the WaitOne() method of the AutoResetEvent class. It'll wait until it gets notified from a secondary thread for completion and this I think should be the optimized way for waiting 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:

Multithreading

Fun while it's not done !!

Up Next
    Ebook Download
    View all
    Learn
    View all