Dear all
I have a communication class which does use
SerialPort to communicate. My first implementation polled the port and was very efficient. Because I hate polling I tried to replace it.
My idea:
- I hook into
SerialPort.DataReceived.
DataReceived will be called from a the
SerialPort thread
- My
DataReceived checks the condition and set an
AutoResetEvent to signaled if the condition meats the criterion
- The main thread waits using
AutoResetEvent.WaitOne().
Problem:
Even while
DataReceived signales
AutoResetEvent, the main thread freezes.
Thanks in advance.
Regards
code fragments:
class CommunicationDeviceSerialPort : CommunicationDevice
{
System.IO.Ports.SerialPort serialPort = new System.IO.Ports.SerialPort();
AutoResetEvent recSynchObj = new AutoResetEvent(false)
private void SerialDataReceivedEvent(object sender, SerialDataReceivedEventArgs e)
{
... deviceBuffer
if (deviceBuffer meats my condition)
recSynchObj.Set();
}
public int Communicate(String Command, int TimeoutMS, out Data)
{
...
serialPort.Write(Command);
bool xSignaled= recSynchObj.WaitOne();
if (xSignaled)
{
...
}
}
}
class FormMain
{
CommunicationDevice commDevice= new CommunicationDeviceSerialPort();
private void DoCommunicate
{
commDevice.Communicate(cmd, 2000, );
}
}