Tip 1: When using SerialPort.Read(buffer, offset, count), where count is the number of bytes you want to read, check the return value, which tells you the number of bytes actually read.

    SerialPort.Read() 的返回值才是真正读到的字节数。


    Tip 2.When using DataReceived event handlers, don’t assume you’ll receive an event for every byte received (assuming you’re using the default ReceivedBytesThreshold of 1)

    DataReceived 事件并不是每收到一个字节就触发一次,而是每次触发后至少能读入一个字节。
    还可以通过设置 ReceivedBytesThreshold 来指定至少收到几个字节就触发 DataReceived 事件。

    解决该问题的方法有两种:

    • 每次触发事件后,通过 BytesToRead 读取有多少字节待读入,再使用 SerialPort.Read(buffer, offset, count)
    • 使用 ReadExisting 直接把待读入的一次读入

    Tip 3. Take care to avoid deadlock when calling Close on the SerialPort in response to a GUI event.

    如果你有个事件处理器正在更新 GUI,同时 GUI 线程又在尝试关闭 SerialPort,就可能发生死锁。
    发生该问题的原因是 Close() 要等待事件更新 GUI 完毕后才关闭串口。

    解决该问题的方法有两种:

    • 把事件处理器里面的 Control.Invoke 换成 Control.BeginInvoke 后者通过异步来避免死锁。基本上涉及到 GUI 的死锁问题都可以通过该方法解决
    • 在一个独立的线程中去调用 serialPort.Close() 关闭串口

    Tip 4. .NET 2.0 isn’t letting you get away with some things, such as attempting to cancel a SerialPort read by interrupting the thread accessing the SerialPort. (Note that pre-2.0, canceling a thread reading from the SerialPort resulted in an exception you could catch but you weren’t warned of worse things going on behind the scenes such as leaked objects.)


    Tip 5. This isn’t a tip as much as an attempt to clear up some confusion we may have caused. SerialPort.ReadByte will either return a byte or throw an exception if a byte can’t be read; it never returns -1.

    SerialPort.ReadByte要么返回一个字节,要么抛出异常,它并不会在读取失败时返回 -1。

    The exceptions SerialPort can return are:

    • InvalidOperationException: port isn’t open 串口未打开
    • TimeoutException: timeout occurred 读取超时
    • IOException: general IO errors; will be accompanied by specific error message
    • UnauthorizedAccessException: access to port denied 串口拒接访问
    • EndOfStreamException: end of stream 流读完了