【发布时间】:2011-06-09 16:44:52
【问题描述】:
我注意到,如果事件触发得太快,我的代码有时会变得不同步。我想知道是否有更好的方法。在正常情况下,DeviceOpenedEvent 在我在 TestDevice 方法中告诉线程到 WaitOne 后触发,但我看到在某些情况下,事件在线程有机会等待之前被触发。
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方法)? -
OpenDevice 是一个异步方法调用。 TestDevice 对设备执行一系列操作,如打开、锁定、开机、关机。
标签: c# .net multithreading concurrency