条件事件等待/ ManualResetEvent

Sea*_*man 3 c# events multithreading synchronization manualresetevent

我知道如何使用ManualResetEvent或同步原语(如Monitor)来等待事件和/或锁,但我想知道是否有办法实现如下所示:

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."; 
}
Run Code Online (Sandbox Code Playgroud)

1)等待1000ms以发生事件X.

2)如果事件发生在1000ms内,则执行路径A.

3)否则,执行路径B.

这基本上是一个条件等待函数,其中条件是我们必须等待多长时间,如果可能的话,实现它的最佳方法是什么?

Jon*_*eet 5

它看起来像你在追求:

return resetEvent.WaitOne(1000) ? "Event occurred within 1000ms"
                                : "Event did not occur within 1000ms";
Run Code Online (Sandbox Code Playgroud)

来自以下文档WaitHandle.WaitOne:

如果当前实例收到信号,则返回值为
true ; 否则,错误.

Monitor.Waitbool以类似的方式返回a .