3

I know how to use the ManualResetEvent or synchronization primitives (like Monitor) to wait for events and/or locks, but I am wondering if there is a way to implement something like the following:

ManualResetEvent resetEvent; 

public string WaitForOneThousandMs()
{
    resetEvent.Wait(1000);

    if (WaitTime(resetEvent) <= 1000)
        return "Event occured within 1000ms."; 
    else
        return "Event did not occur within 1000ms."; 
}

1) Wait for 1000ms for an event X to occur

2) If event occurs within 1000ms, execute path A

3) Otherwise, execute path B

This is basically a conditional waiting function where the condition is how long we had to wait, what would be the best way to implement it, if possible?

Sean Thoman
  • 7,429
  • 6
  • 56
  • 103

1 Answers1

5

It looks like you're after:

return resetEvent.WaitOne(1000) ? "Event occurred within 1000ms"
                                : "Event did not occur within 1000ms";

From the docs for WaitHandle.WaitOne:

Return value
true if the current instance receives a signal; otherwise, false.

Monitor.Wait returns a bool in a similar fashion.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Quick follow-up question: If the Set() method is called on ManualResetEvent BEFORE the WaitOne() method even starts waiting, will the WaitOne() method immediately return true? – Sean Thoman Aug 02 '12 at 18:34