SIGN UP MEMBER LOGIN:    
ARTICLE

Optimizing Wait in MultiThreading Environment - C#

Posted by Amit Choudhary Articles | Visual C# July 25, 2011
Here you will see optimization of waiting in a MultiThreading environment using the AutoResetEvent class with C#.
Reader Level:


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 !!

Login to add your contents and source code to this article
share this article :
post comment
 

A little more of an explanation would help I think. A suggestion for this article or another article would be to show how to use an event for the main thread to be able to gracefully stop the secondary thread. And you could show how the main thread can notify the worker thread when there is work to do, so then the worker thread would have two events to wait for. Well, I suppose that would be more appropriate in a separate more advanced article.

Posted by Sam Hobbs Jul 25, 2011

Thanks Sam.. I appreciate your views here...well in order to exploring the MultiThreading concepts I just found some wonderful facts and gave a thought to share it.. if you saying then i'll try to write an extension for this article anyway.. :)

Posted by Amit Choudhary Jul 25, 2011

Good article; I certainly have used events many times. This is an article that I might have written if I thought of it. I think a bit more explanation would help beginners.

Posted by Sam Hobbs Jul 25, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Become a Sponsor