I have a .NET C# class which uses System.IO.Ports.SerialPort
for serial port communication. It includes a thread which continuously read the serial port in a loop.
I have always thought that using Exceptions as part of normal program flow was bad, but searching the web I see many examples using blocking Read and TimeoutException
to wait for incoming data, like this:
while (true)
{
try
{
serialPort.Read(buffer, offset, count);
/* Processing code here */
}
catch (TimeoutException)
{ }
}
Wouldn't it be better to check SerialPort.BytesToRead()
before issuing the Read
, like in this example:
while (true)
{
if (serialPort.BytesToRead() <= 0)
{
/* Wait for event signal or similar. */
}
serialPort.Read(buffer, offset, count);
ProcessData();
}