tags:

views:

139

answers:

4

I have a WaitHandle and I would like to know how to check if the WaitHandle has already been set or not.

Note: I can add a bool variable and whenever Set() method is used set the variable to true, but this behaviour must be built in WaitHandle somewhere.

Thanks for help!

+5  A: 

Try WaitHandle.WaitOne(0)

If millisecondsTimeout is zero, the method does not block. It tests the state of the wait handle and returns immediately.

SwDevMan81
*Ashamed* Thanks!
MartyIX
+1 Good clear answer. Nice and simple, though I would suggest changing "Try" to "Use". As it stands, you seem unsure of your answer.
Jeff Yates
The only issue is that for some WaitHandles (auto-reset event, semaphore), the ready state will actually be reset by waiting on it.
Ben Voigt
+1  A: 

Use one of the Wait... methods on WaitHandle that takes a timeout value, such as WaitOne, and pass a timeout of 0.

Jeff Yates
A: 

You can use the WaitOne(int millisecondsTimeout, bool exitContext) method and pass in 0 for the timespan. It will return right away.

bool isSet = yourWaitHandle.WaitOne(0, true);
Miky Dinescu
Why should they use the one that takes an `exitContext` value? Considering that there are alternatives which do not require this field, you should explain its necessity.
Jeff Yates
+1  A: 
const int DoNotWait = 0;

ManualResetEvent waitHandle = new ManualResetEvent(false);                   

Console.WriteLine("Is set:{0}", waitHandle.WaitOne(DoNotWait));

waitHandle.Set(); 

Console.WriteLine("Is set:{0}", waitHandle.WaitOne(DoNotWait));   

Output:

Is set:False

Is set:True

chibacity
Why use a keyword for the variable? It's unnecessary and makes your answer harder to read.
Jeff Yates
@Jeff Sure, it's just a hard thing to name for some sample code, and I've been writing a lot of code today.
chibacity
@chibacity: it's easy to write something other than event. `waitHandle`, `resetEvent`, `mre`, `myEvent`. The list is endless and it would make your example better.
Jeff Yates
@Jeff You have no idea of my state of mental exhaustion at the moment - but I will comply! :)
chibacity
@chibacity: I can sympathise but if a job's worth doing, it's worth doing well. +1
Jeff Yates
@Jeff Cheers for the kick up the bum, you are quite right. :)
chibacity