Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new AutoResetEvent (true) Usages in C#?

I was wondering ,

Why would I ever want to pass a true in the ctor of AutoResetEvent ?

I create a waitHandle so that anyone who will call WaitOne() will actually wait.

If I instance it with a true , it will be as if it was immediatly signaled - which is like a normal flow without waiting.

  EventWaitHandle _waitHandle = new AutoResetEvent (false);

void Main()
{
  new Thread (Waiter).Start();
    Thread.Sleep (1000);                   
    _waitHandle.Set();                    

Console.ReadLine();
}
  void Waiter()
  {
    Console.WriteLine ("AAA");
    _waitHandle.WaitOne();                 
    Console.WriteLine ("BBBB");
  }

output :

AAA...(delay)...BBB

changing to : EventWaitHandle _waitHandle = new AutoResetEvent (true); and the output will be :

AAABBB

Question :

  • Why would I ever want to do this ? ( passing true) ?
like image 359
Royi Namir Avatar asked Dec 05 '12 08:12

Royi Namir


1 Answers

The scenario would be that the first thread that calls WaitOne should immediately pass through, without blocking.

Check the Silverlight documentation for AutoResetEvent (strangely enough the doc is not the same on the .Net versions):

Specifying true for initialState creates an AutoResetEvent in the signaled state. This is useful if you want the first thread that waits for the AutoResetEvent to be released immediately, without blocking."

like image 163
jeroenh Avatar answered Oct 05 '22 01:10

jeroenh