Domanda

I am trying to setup some comms with a device where you can send a command and receive a response. I do however want to ensure that I control a timeout flag to prevent indefinite wait times.

I did something like this:

private volatile EventWaitHandle _signal;

public void Send()
{
    // Do something

    _signal.WaitOne(30000);

    // Continue with something else

    _signal.Reset();
}

public void Receive() 
{
    _signal.Set();
}

My question is, if I have multiple threads (let's say 2 for this example) that can access the Send method and the following scenario:

Thread A:

// Sends a "listen" command, but no response is received 
Send();

Thread B:

// Sends a "cancel" command and response (success) is received
Send();

I get inconsistent results, i.e. sometimes both threads continue when I get a response for the second command (cancel) which I can understand, but sometimes the first thread will hit the 30000ms timeout - which I cannot explain.

Any advice as to what I am missing and/or doing wrong?

È stato utile?

Soluzione

An EventWaitHandle is not the appropriate synchronization object here. You require mutual exclusion so that only one thread can be in a state where it sent a command and is waiting for the response. In other words, threads must strictly take their turn to talk to the device.

A ManualResetEvent doesn't give you that guarantee, as soon as you call Set() then all the threads that are blocking on the WaitOne() call will be unblocked. If that's more than one then your program will malfunction when two or more threads try to send a command at the same time.

A Mutex provides MUTual EXclusion. That's how it got its name.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top