45

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!

MartyIX
  • 27,828
  • 29
  • 136
  • 207
  • My answer was only seconds before SwDevMan's which is much clearer and includes the documentation quote, so I'm deleting it. However, I still wonder "Are you dealing with an auto-reset event that might already have been reset, or that the test code must not reset?" – Ben Voigt Jul 24 '10 at 18:19

4 Answers4

61

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
  • 48,814
  • 22
  • 151
  • 184
  • +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 Jul 22 '10 at 20:31
  • 9
    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 Jul 24 '10 at 18:21
  • @Vivin joy - `millisecondsTimeout` is the parameter name to the `WaitOne` call, please see the link. Its a quote taken from the Remarks section – SwDevMan81 Sep 20 '12 at 13:32
  • @MartinVseticka Don't be ashamed! I came here with the same question. The answer is perhaps guessable, but by no means self-evident. – Tim Long May 26 '19 at 09:07
  • It doesn't just check if the wait handle is AutoResetEvent! It actually changes its state to true. – Mohammad Nikravan Sep 27 '21 at 19:25
7
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

Community
  • 1
  • 1
Tim Lloyd
  • 37,954
  • 10
  • 100
  • 130
2

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

Jeff Yates
  • 61,417
  • 20
  • 137
  • 189
1

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);
Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
  • 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 Jul 22 '10 at 20:34
  • Online help for VS2005 only shows WaitOne(), WaitOne(int,bool), and WaitOne(TimeSpan,bool). So, it's likely they didn't find WaitOne(int) – Lee Louviere Nov 15 '11 at 16:09