views:

98

answers:

1

I want to clarify how the following code works.I have itemized my doubts to get your reply.

class AutoResetEventDemo
{
    static AutoResetEvent autoEvent = new AutoResetEvent(false);

    static void Main()
    {
        Console.WriteLine("...Main starting...");

        ThreadPool.QueueUserWorkItem
        (new WaitCallback(CodingInCSharp), autoEvent);

        if(autoEvent.WaitOne(1000, false))
        {
            Console.WriteLine("Coding singalled(coding finished)");
        }
        else
        {
            Console.WriteLine("Timed out waiting for coding"); 
        }

        Console.WriteLine("..Main ending...");

        Console.ReadKey(true);
    }

    static void CodingInCSharp(object stateInfo) 
    {
        Console.WriteLine("Coding Begins.");
        Thread.Sleep(new Random().Next(100, 2000));
        Console.WriteLine("Coding Over");
       ((AutoResetEvent)stateInfo).Set();
    }
}
  1. static AutoResetEvent autoEvent = new AutoResetEvent(false);

    At initial stage signal is set to false.

  2. ThreadPool.QueueUserWorkItem(new WaitCallback(CodingInCSharp), autoEvent);

    Select a thread from ThreadPool and make that thread to execute CodingInCSharp. The purpose of WaitCallback is to execute the method after Main() thread finishes its execution.

  3. autoEvent.WaitOne(1000,false)

    Wait for 1 sec to get the signal from "CodingInCSharp") Incase if i use WaitOne(1000,true), will it kill the thread it received from threadpool?

  4. If I did not set ((AutoResetEvent)stateInfo).Set(); will the Main() indefinitely wait for signal?

+1  A: 

The WaitCallback is executed in concurrently to the Main method as soon as a threadpool thread becomes available.

The Main method waits 1 second for the CodingInCSharp method on the threadpool thread to set the signal. If the signal is set within 1 second, the Main method prints "Coding singalled(coding finished)". If the signal is not set within 1 second, the Main method aborts waiting for the signal and prints "Timed out waiting for coding". In both cases the Main method proceeds to wait for a key to be pressed.

Setting a signal or reaching a timeout does not "kill" a thread.

The Main method will not wait indefinitely if the signal is not set, because waiting for the signal is aborted if the signal is not set within 1 second.

dtb