我注意到,如果事件触发得太快,我的代码有时会不同步。我想知道是否有更好的方法。在正常情况下,DeviceOpenedEvent在将线程告诉WaitDene的TestDevice方法后触发,但在某些情况下,在线程有机会等待之前事件被触发。同步事件
protected AutoResetEvent TestAutoResetEvent = new AutoResetEvent(false);
public EventEnum WaitForEvent = EventEnum.None;
bool TestDevice()
{
OpenDevice();
WaitForEvent = EventEnum.DeviceOpened;
TestAutoResetEvent.WaitOne();
WaitForEvent = EventEnum.NoWait;
//Continue with other tests
}
void DeviceOpenedEvent()
{
if (WaitForEvent == EventEnum.DeviceOpened)
TestAutoResetEvent.Set();
}
在正常情况下,它看起来像这样:
- 打开设备
- 了WaitOne()
- DeviceOpenedEvent发生
- 集()
这是我有时看到我的日志:
- 打开设备
- DeviceOpenedEvent发生
- 了WaitOne()这里基本上停留永远
不应该'OpenDevice'方法指定设备何时打开(而不是'TestDevice'方法)? – 2011-06-09 16:55:16
OpenDevice是一个异步方法调用。 TestDevice在设备上执行一系列操作,例如打开,锁定,打开电源,关闭电源。 – Robert 2011-06-09 16:59:49