Search code examples
c#.netserial-porttimeoutexception

Checking SerialPort.BytesToRead vs using TimeoutException in a read loop?


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();
}

Solution

  • The second approach is definitely better. Exceptions should not be used to control normal program flow.

    Additionally, the first approach will really clutter your debugging experience, especially if you set your IDE to break on every thrown exception.