Conditional event waiting / ManualResetEvent
-
24-06-2021 - |
Pergunta
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?
Solução
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.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow