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 recommanded 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 missing some data sometimes. 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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…