new AutoResetEvent (true) Usages in C#?
Asked Answered
M

3

15

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) ?
Medlar answered 5/12, 2012 at 8:48 Comment(0)
A
11

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

Armond answered 5/12, 2012 at 8:56 Comment(2)
Word "release" is very confusing. It seems like you are releasing thread CPU time-slice, but you are actually letting it continue working past .WaitOne() call.Hanyang
You're right, it is confusing. I added a comment on that documentation page.Armond
C
9

There's a good explanation here: Signaling with Event Wait Handles.

To paraphrase, the wait handle is like a turnstile, with the callers of WaitOne being like a line of people queuing at the turnstile. Each time Set is called, the turnstile allows one person through (usually in the order that they queued, but sometimes not, due to OS quirks).

If it is constructed with 'true', then the turnstile is already open, but for only one person, so that the first caller of WaitOne will be 'let through' straight away, but any subsequent callers will still have to queue.

Obviously none of this would be applicable if you only have one caller of WaitOne, and so the 'true' option would be moot.

Carbonation answered 5/12, 2012 at 9:7 Comment(0)
H
1

Sure.

One requirement - a thread X must run on app start and every 10 secs thereafter. A timed WaitForSingleObject(myARE,10000) would do the job. Initializing the ARE to 'true' would ensure the thread runs on startup.

Edit:

myARE.WaitOne(10000);

Sorry - I dropped out of C# mode into WINAPI, briefly :(

Hysterogenic answered 5/12, 2012 at 9:46 Comment(1)
Thanks @Armond - I tried to add the code block myself but my ISP is acting up again today, DNS up/down intermittently :(Hysterogenic

© 2022 - 2024 — McMap. All rights reserved.