问题
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
) ?
回答1:
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
forinitialState
creates anAutoResetEvent
in the signaled state. This is useful if you want the first thread that waits for theAutoResetEvent
to be released immediately, without blocking."
回答2:
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.
回答3:
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 :(
来源:https://stackoverflow.com/questions/13719286/new-autoresetevent-true-usages-in-c