我必须等待事件被触发。我最初的解决方案是使用AutoResetEvent
和WaitOne()
,但事件是总是在等待超时结束后触发。所以我回到了下面的方法,但我仍然有同样的问题。超时结束后2或3秒,无论超时是什么,事件都会被触发。超时结束后触发事件
_wait = true;
_delayedResponse = null;
var thread = new Thread(delegate
{
while (_wait)
{
Thread.Sleep(500);
if (_delayedResponse != null)
return;
}
});
thread.Start();
var received = thread.Join(_responseTimeout);
_wait = false;
if (!received)
throw new TimeoutException(
"Timeout for waiting for response reached.");
return _delayedResponse;
这里是事件处理代码:
private void OnResponseArrived(object sender, ResponseEventArgs args)
{
_delayedResponse = args.VerificationResponse;
}
事件本身是由调用上述功能的其他功能触发。 基本上它看起来是这样的:
var result = DoStuff(); // Library function that is responsible for the event
if (result.Status == Status.Wait)
Wait(); // Function above
有没有人有一个想法是什么原因导致这个问题,我该如何解决呢?
编辑:不再相关。转发了OnResponseArrived事件,因为我没有及时发现其他解决方案。
你从哪里触发事件? – 2011-01-27 12:35:59
什么意思是“事件被触发,无论超时是什么”? `ResponseArrived`事件?你确定这个事件是从另一个线程发起的吗? – Groo 2011-01-27 12:39:32
谢谢你的评论。我更新了这个问题。 – xsl 2011-01-27 12:39:38