Reputation: 17556
i am little confused about the manual reset event's wait one method , consider below scenarion
static object objLock = new object();
static int counter = 5;
static ManualResetEvent mEvent = new ManualResetEvent(false);
static void Main(string[] args)
{
///LeftShifting(10, 4);
// RightShifting(3, 1);
// Xoring(0001, 1001);
// ExcahnageValuesWithXoring(10, 20);
// ReverseBits(0);
Thread.CurrentThread.Name = "Main Thread";
for(int i=0;i<5;i++)
{
Thread t = new Thread(new ThreadStart(DoSomeLongWork));
t.Name = i.ToString();
t.Start();
}
Console.WriteLine("Current thread is " + Thread.CurrentThread.Name);
mEvent.WaitOne();
Console.WriteLine("Current thread is " + Thread.CurrentThread.Name);
Console.WriteLine("Completed Long Running Process...");
Console.ReadLine();
}
private static void DoSomeLongWork()
{
Console.WriteLine("Starting Long Running Process...On " + Thread.CurrentThread.Name);
Thread.Sleep(5000);
Interlocked.Decrement(ref counter);
Console.WriteLine("Ending Long Running Process...On " + Thread.CurrentThread.Name);
if (counter == 0)
mEvent.Set();
}
my question is when i call mEvent.Waitone() is it going to block 'Main Thread' or the one of the executing child thread.
Upvotes: 1
Views: 649
Reputation: 1500903
It blocks the main thread. That's the only one it can block. You can't force another thread to sleep. The main thread will wait for the other thread to "set" the event. This is very much like Monitor.Wait
/Pulse
.
Upvotes: 4
Reputation: 158319
mEvent.WaitOne()
will block the main thread until one of the child threads calls mEvent.Set()
.
Upvotes: 1