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?