2

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!

DocSwag
  • 21
  • 2
  • 1
    Check out this solution https://stackoverflow.com/questions/41777981/serialport-basestream-readasync-drops-or-scrambles-bytes-when-reading-from-a-usb?rq=1 – Selthien Jul 23 '19 at 15:58
  • It will depend on the specifications of the equipment connected to the COM port. If the specification, for example, an interval of 500ms is sufficient, there may be no problem with DataReceived Event and Read Method. – kunif Jul 23 '19 at 21:51

0 Answers0