【问题标题】:Conditional event waiting / ManualResetEvent条件事件等待/ManualResetEvent
【发布时间】:2012-08-02 18:24:06
【问题描述】:

我知道如何使用 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."; 
}

1) 等待 1000ms 让事件 X 发生

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

3) 否则,执行路径B

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

【问题讨论】:

    标签: c# multithreading events synchronization manualresetevent


    【解决方案1】:

    看起来你在追求:

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

    来自WaitHandle.WaitOne 的文档:

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

    Monitor.Wait 以类似的方式返回 bool

    【讨论】:

    • 快速跟进问题:如果在 WaitOne() 方法甚至开始等待之前在 ManualResetEvent 上调用 Set() 方法,WaitOne() 方法会立即返回 true 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多