SerialPort ReadTimeout是5秒,但超时需要432秒

时间:2014-03-24 21:02:23

标签: c# exception blocking

我有一些代码在串口上寻找一个字节,我正在尝试测试没有数据时会发生什么。

byte[] startByteArray = new byte[1];

// Find a start byte
try
{
    do
    {
        Logger.trace("Starting read at " + DateTime.Now.ToString());
        Logger.trace("comm.ReadTimeout = " + comm.ReadTimeout);
        comm.Read(startByteArray, 0, 1);
        Logger.trace("Found a byte: " + startByteArray[0].ToString("X2"));

        if((new TimeSpan(DateTime.UtcNow.Ticks - startTime)).TotalMilliseconds > comm.ReadTimeout)
            throw new TimeoutException("Invalid Data: Start byte never found, but others were: " + startByteArray[0].ToString("X2"));

    } while (!isStartByte(startByteArray[0]));

}
catch (TimeoutException ex)
{
    Logger.trace("Caught exception at " + DateTime.Now.ToString());
    Logger.trace("comm.ReadTimeout = " + comm.ReadTimeout);
    Logger.trace("Exception = " + ex.Message);

    if(ex.Message.Contains("Invalid Data"))
        driverEvent = new DriverEvent(DriverEventCode.INVALID_DATA, ex.Message, DateTime.UtcNow.Ticks);
    else
        driverEvent = new DriverEvent(DriverEventCode.NO_DATA, "No bytes received in " + comm.ReadTimeout + " milliseconds: " + ex.Message, DateTime.UtcNow.Ticks);
    return null;
}

生成的一些输出如下:

03.24 16:04:22 TRACE:COM301.295           Starting read at 3/24/2014 4:04:22 PM
03.24 16:04:22 TRACE:COM301.295           comm.ReadTimeout = 5000
03.24 16:11:34 TRACE:COM301.295           Caught exception at 3/24/2014 4:11:34 PM
03.24 16:11:34 TRACE:COM301.295           comm.ReadTimeout = 5000
03.24 16:11:34 TRACE:COM301.295           Exception = The operation has timed out.
03.24 16:11:34 ERROR:COM301.280           NO_DATA error received: No bytes received in 5000 milliseconds: The operation has timed out. was generated.
...
03.24 16:12:11 TRACE:COM301.287           Starting read at 3/24/2014 4:12:11 PM
03.24 16:12:11 TRACE:COM301.287           comm.ReadTimeout = 5000
03.24 16:19:23 TRACE:COM301.287           Caught exception at 3/24/2014 4:19:23 PM
03.24 16:19:23 TRACE:COM301.287           comm.ReadTimeout = 5000
...
03.24 16:20:00 TRACE:COM301.293           Starting read at 3/24/2014 4:20:00 PM
03.24 16:20:00 TRACE:COM301.293           comm.ReadTimeout = 5000
03.24 16:27:13 TRACE:COM301.293           Caught exception at 3/24/2014 4:27:13 PM
03.24 16:27:13 TRACE:COM301.293           comm.ReadTimeout = 5000

ReadTimeout设置为5000毫秒;为什么要花7分钟?我无法想到另一个将持有串口人质的线程。

更新

所有控制线都保持高位;由于这个原因,SerialPort类可以忽略ReadTimeout吗?

0 个答案:

没有答案