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();
}
}
static AutoResetEvent autoEvent = new AutoResetEvent(false);
At initial stage signal is set to false.
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.
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?
If I did not set
((AutoResetEvent)stateInfo).Set();
will the Main() indefinitely wait for signal?