1

I have this code:

private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
    while(_serialPort.BytesToRead > 0)
    {
       var count = _serialPort.BytesToRead;
       var bytes = new byte[count];
       _serialPort.Read(bytes, 0, count);
       AddBytes(bytes);
    }
}

Code is taken from Serial Port Polling and Data handling.

My question is about the While loop. When does "_serialPort.BytesToRead" update? Meaning, if the method above is an event driven method, and I use "_serialPort.Read", doesn't it clear all serial port buffer? If the answer is no, this code can create an endless loop, can't it?

Community
  • 1
  • 1
AnR
  • 81
  • 7
  • no it's fine, `_serialPort.Read` will of course clear the buffer, maybe some more will have been received after but that's fine too - only you should inspect the return of `_serialPort.Read` - just in case it did not really read all `count` bytes – Random Dev Apr 21 '15 at 08:19

0 Answers0