从MSDN“如果没有等待的线程,等待句柄将保持信号状态,直到线程尝试等待它,或者直到调用其Reset
方法。”
EventWaitHandle MyWaitHandle = new AutoResetEvent(false);
线程#1:
public void Method1()
{
//do something
//wait for the signal or timeout
MyWaitHandle.WaitOne(10000);
//do something else on receiving signal or after timeout
}
线程#2:
//this would be called when there is a response from the external app
public void Method2()
{
//do something
//send the signal to waiting thread
MyWaitHandle.Set();
}
在我的应用程序中,线程#1正在向外部应用程序提交请求并等待信号或超时。如果从外部应用程序收到响应,则线程#2设置等待句柄。即使在超时后也可以调用此set
。我的问题是
1)很可能在超时后调用Method2
导致设置信号。这是否意味着,如果将来有线程#1的请求,WaitOne(10000)
无效并将立即释放?
2)如果超时,我是否仍然在set
中呼叫Method2
?这会给Thread#1带来任何问题吗?
答案 0 :(得分:2)
为什么不确保在等待之前总是重置等待句柄?
public void Method1()
{
// Reset the wait handle I'll be using...
MyWaitHandle.Reset();
//do something
//wait for the signal or timeout
MyWaitHandle.WaitOne(10000);
//do something else on receiving signal or after timeout
}