MartyIX
MartyIX

Reputation: 28648

How to check if the WaitHandle was set?

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!

Upvotes: 45

Views: 21888

Answers (4)

SwDevMan81
SwDevMan81

Reputation: 49978

Try WaitHandle.WaitOne(0)

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

Upvotes: 63

Tim Lloyd
Tim Lloyd

Reputation: 38434

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

Upvotes: 7

Jeff Yates
Jeff Yates

Reputation: 62367

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

Upvotes: 2

Mike Dinescu
Mike Dinescu

Reputation: 55720

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

Upvotes: 1

Related Questions