Reputation: 201
I've been using the SerialPort
class for a little while in an application that communicates with some external hardware that I've designed. During the debugging process of said hardware, I found a few things to be unreliable, and I recently stumbled across this which seems to be onto something.
I'm trying to implement this into my application, however I have two questions about receiving data...
So, in the article I linked, the author mentions that the DataReceived
event is problematic, and shows a typical code sample of how it could be used...
port.DataReceived += port_DataReceived;
// (later, in DataReceived event)
try {
byte [] buffer = new byte[port.BytesToRead];
port.Read(buffer, 0, buffer.Length);
raiseAppSerialDataEvent(buffer);
}
catch (IOException exc) {
handleAppSerialError(exc);
}
And then what the author considers to be the correct method is shown...
byte[] buffer = new byte[blockLimit];
Action kickoffRead = null;
kickoffRead = delegate {
port.BaseStream.BeginRead(buffer, 0, buffer.Length,
delegate (IAsyncResult ar) {
try {
int actualLength = port.BaseStream.EndRead(ar);
byte[] received = new byte[actualLength];
Buffer.BlockCopy(buffer, 0, received, 0, actualLength);
raiseAppSerialDataEvent(received);
}
catch (IOException exc) {
handleAppSerialError(exc);
}
kickoffRead();
}, null);
};
kickoffRead();
My questions revolve around the use of BaseStream.BeginRead
; where abouts in my class that would be reading the data should this be put? My first thought was in the DataReceived
event, as in the first example showing how NOT to use the SerialPort
class the author mentions that the code is in the DataReceived
event in the comment, but for the sample showing a better way the author makes no mention of where the code should be so I thought he was still referring to the DataReceived
event, but then the author mentioned that the DataReceived
event itself has problems, so...? Any guidance here would be great, and appologies if its obvious!
If I've not mentioned something that would benefit anyone trying to answer this then by all means let me know. Thanks in advance for any guidance and/ or feedback!
Upvotes: 4
Views: 2060
Reputation: 9508
It's a recursive function, so you call this code only ONCE after opening the port, and it will continue to repeat itself without blocking execution (or requiring a DataReceived event handler).
Upvotes: 5