I'm currently writing a C# program that needs to read and write data over the serial port. I was going to use the .NET SerialPort class's DataReceived, Read, etc. methods to accomplish this, but then I saw this post talking about how these methods are really badly written and shouldn't be used, and that instead I use use the BaseStream property. I figured out that for writing to the serialport that I can do this:
byte[] buffer = { size };
await comPort.BaseStream.WriteAsync(buffer, 0, buffer.Length);
and for reading I can use this:
byte[] buffer = new byte[size];
int read = 0;
while (read < size)
read += await comPort.BaseStream.ReadAsync(buffer, read, size-read);
However, I need to periodically call the read function to see if the serialport has received more data I need to collect, and I'm not sure how I should do that. Is creating a timer that calls a function every once in a while a good solution (and if so, how often should I call it? Every 500 ms?)?
Furthermore, I found the code for reading the data from some comment on the post I linked, and the thing I'm not sure about is what to use for size
. I would've used the SerialPort.BytesToRead()
method, but according to the post that method is bad as well, so I'm not sure what else I could use... Also, is there any need for a read/write timeout? I honestly have no clue if the code needs one. Any suggestions would be greatly appreciated!