jcurl / RJCP.DLL.SerialPortStream

SerialPortStream is an independent implementation of System.IO.Ports.SerialPort and SerialStream for better reliability and maintainability. Default branch is 2.x and now has support for Mono with help of a C library.
Microsoft Public License
624 stars 197 forks source link

Hangs on framing errors #85

Closed ohjohnsen closed 5 years ago

ohjohnsen commented 5 years ago

When receiving data on one port that's in a different baud rate than the configured baud rate, the serial port instance will eventually hang.

In my application, I'm using one SerialPortStream instance to poll data from hardware A on baud rate 57600, and on another SerialPortStream instance I'm receiving streamed data from hardware B on baud rate 38400 (55 bytes 20 times per second). If the operator switches the two configured ports (in effect streaming in 1.1 kBps at the wrong baudrate), the instance polling data from hardware A will hang, forcing the operator to restart the application.

How can I prevent this? I'm trying to dispose the instance in a ErrorReceivedHandler, and this works a few times but eventually fails and hangs.

Adding a screenshot from BeyondCompare, where I'm comparing the SerialPortStream object in a working state and in a hanged state.

2019-02-11 13_12_55-new text compare_ - text compare - beyond compare

ohjohnsen commented 5 years ago

This is the best method I've been able to find to avoid hanging. But it still hangs after a while.

Polling interface: https://dotnetfiddle.net/RCNqaE

Streaming interface: https://dotnetfiddle.net/Lz3tAa

Just connect the two using two hardware serial ports and a null-modem cable, or a set of virtual serial ports using e.g. com0com.

jcurl commented 5 years ago

You shouldn't dispose the SerialPortStream in an event handler, the object is still in use. You should at least close it, and let your reader threads get a value of 0 indicating that the port is closed to exit, which you can then dispose.