SerialPort.Read(…) does not respect ReadTimeOut

2020-04-10 02:44发布

问题:

Got a bug in some legacy code which communicates with a payment terminal.

Just before a new payment is started, the code attempts to clear the internal read buffer of the SerialPort.

I trimmed the code down to the bare minimum. It uses the .NET SerialPort type. A read timeout of 50ms is set. Then it reads 512 bytes and continues doing so until no more bytes are read or until a TimeoutException is thrown.

We added a bunch of logging and it showed that the call to the first Read(...) method sometimes takes 10 - 15 minutes, even with a timeout of 50ms. Then a TimeoutException is thrown and the application continues. But during the Read(...) the application hangs.

This doesn't always happen, Windows 2000 machines seem more prone to this error for some reason.

public class Terminal
{
    private SerialPort _serialPort = new SerialPort();

    public void ClearReadBuffer()
    {
        try
        {   
            _serialPort.ReadTimeout = 50;
            int length;
            do
            {
                var buffer = new byte[512];
                length = _serialPort.Read(buffer, 0, 512);
            } while (length > 0);
        }
        catch (TimeoutException) {}
    }
}

Any help is appreciated.

PS: Most error reports are coming from W2K machines where the device is connected to an EdgePort, which simulates a bunch of virtual COM ports. Its driver creates a bunch (8 or so) local COM port.

But we also have reports from Windows 7. We can also reproduce the issue if we directly connect the device to the PC (no EdgePort). However not as often and when it happens the delay it not 10 minutes, but more like 1 - 2 minutes.

Update: Tried a lot of things to fix this. Was hard to reproduce, but occurred quite often in the field because there it is distributed on thousand of PCs. Actually replaced the .NET 2.0 SerialPort type with another open source version. Worked without a problem on the one PC where we could actually reproduce it like 60 - 70% of the time. But alas, during a pilot test in production the problems still continued to occur.

The code for the payment terminal was written a couple of years earlier and I ported it to anonther application. During the port I re-factored some code, but kept the original functionality. When communicating with the terminal the code would:

  1. Fire off another thread from the thread pool
  2. Send the message to the device
  3. Read from the serial port until a response had been received or a timeout occurred.

Meanwhile the main thread had a while loop which contained a Thread.Sleep(50) and an Application.DoEvents() call (yuck!). I refactored this whole "wait loop" out of it and made use of a WaitHandle (AutoResetEvent / ManualResetEvent). I just waited until this handle was set. Worked without a problem, but on certain PCs all serial port communication would freeze for minutes until something triggered it. Re-enabled the Application.DoEvents() way of working and the problems were gone.

It is still in there unfortunately, a riddle to me why it is required here and why it causes such severe side effects. The applications supports 5 other types of serial port devices. Communicating with these devices never required anything like this.

回答1:

maybe adding a test on port's 'bytes to read' may help steer clear of badly coded drivers:

length = (_serialPort.BytesToRead > 0) ? _serialPort.Read(buffer, 0, 512) : 0;

better still, use

_serialPort.DiscardInBuffer();

instead!