I've read a lot of questions here about how to read data from serial ports using the .NET SerialPort class but none of the recommended approaches have proven completely efficient for me.
Here is the code I am using for now:
SerialPort port = new SerialPort("COM1");
port.DataReceived += new SerialDataReceivedEventHandler(MyDataReceivedHandler);
And the event handler:
void MyDataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int count = port.BytesToRead;
byte[] ByteArray = new byte[count];
port.Read(ByteArray, 0, count);
}
But I am still sometimes missing data. I've tried different way of reading the data in the event handler but with no luck.
As the .NET 4.5 brings new possibilities to do some asynchronous tasks, like with the ReadAsync method that seems to be useable on a SerialPort stream, I'm curious to see what would be the recommended approach to handle those cases.