I have an open SerialPort and receive data through the DataReceived event.
Is there any way to detect if the SerialPort gets disconnected?
I tried the ErrorReceived and PinChanged events but no luck.
In addition to that, SerialPort.IsOpen returns true when physically disconnected.
USB-serial ports are a huge pain. See, for example, this question. I’m not sure whether it really was fixed with .NET 4.0, but back in the day I tried to deal with the problem of disconnections crashing the whole program with something like this:
Apologies to whoever I adapted this from, it seems I failed to make a note of it in my code. The problem apparently stemmed from how .NET handled the underlying stream in the case of the serial port disappearing. It seemed you couldn’t close the stream after the serial port is disconnected.
Another strategy I used was to create a small program that did just the serial communication part and exposed a WCF service for my main program to connect to. That way, when the USB-serial adapter flakes out and crashes the communication program, I can just automatically restart it from my main program.
Finally, I don’t know why nobody ever marketed a locking USB port to avoid the whole accidental disconnection problem, especially with USB-serial adapters!