This is a mirror of official site: http://jasper-net.blogspot.com/

Optimizing wait in MultiThreading Environment - C#

| Monday, July 25, 2011
While working in Multithreading environment the primary thread has to wait until its 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 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();
        }


Read more: C# Corner
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://www.c-sharpcorner.com/UploadFile/vendettamit/8461/

Posted via email from Jasper-net

0 comments: