Event sync

I noticed that sometimes my code becomes out of sync if the event fires too fast. I was wondering if there is a better approach. In a normal scenario, DeviceOpenedEvent fires after I pass the WaitOne thread in the TestDevice method, but I saw in some cases when the event fires before the thread can wait.

    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();                           
    }

Under normal circumstances, it looks like this:

  • Open device
  • WaitOne ()
  • Applies DeviceOpenedEvent.
  • Install ()

This is what I sometimes see in my magazines:

  • Open device
  • Applies DeviceOpenedEvent.
  • WaitOne () Essentially stuck here forever
+3
source share
2 answers

OpenDevice ( ), , . :

    OpenDevice(); // Async: may finish before the next line executes!
    WaitForEvent = EventEnum.DeviceOpened;

, DeviceOpenedEvent , , WaitForEvent - EventEnum.None:

if (WaitForEvent == EventEnum.DeviceOpened)         
    TestAutoResetEvent.Set(); 

, , , . , , :

protected AutoResetEvent deviceOpenedEvent = new AutoResetEvent(false);
protected AutoResetEvent deviceLockedEvent = new AutoResetEvent(false);

bool TestDevice() {
    OpenDevice();
    // Do some unrelated parallel stuff here ... then
    deviceOpenedEvent.WaitOne();
    LockDevice();
    deviceLockedEvent.WaitOne();
}

void DeviceOpenedEvent() {
    deviceOpenedEvent.Set();                           
}

, OpenDevice: deviceOpened.Set(), . OpenDevice, auto reset TestDevice, .

+2

. AutoResetEvent :

WaitOne, AutoResetEvent state, .

WaitOne, :

AutoResetEvent waitHandle = new AutoResetEvent(false);
waitHandle.Set();
waitHandle.WaitOne();
Console.WriteLine("After WaitOne");
+1

All Articles