Search code examples
c#.netmultithreadingautoresetevent

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) ?

Solution

  • 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."