Closed ohjohnsen closed 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.
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.
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.