Reputation: 19
I am trying to detect whether the serial connection still exists or is broken down. How to detect live serial port connection in c#? Can the SerialPort.PinChanged
Event be used for the same?
Upvotes: 0
Views: 1086
Reputation: 941495
The term "life" has no useful meaning on serial ports. They are very primitive devices that date back to the stone-age of computing. It is where you plugged in your ASR-33 teletype to start banging in your Fortran program. There is no logical connection state and no error recovery, there is no way to share a serial port between multiple programs. Just a raw byte stream, it sits at the very bottom of the OSI model, implementing the physical layer.
It is never useful to use the IsOpen property, you want to immediately Open() the port so no other program can steal the port away from you. Don't call Close() until the very end of the program. Or never, Close() has several gritty deadlock problems.
The electrical standard does include handshake signals, about as close you could get to discover what is happening on the other end of the cable. The SerialPort.DsrHolding property is true when the device has turned on its DTR signal and can usually be interpreted as a power-on signal. Not every device implements it however. Not initializing the SerialPort.Handshake property is a standard bug and the core reason why you don't get a TimeoutException when writing to the port when it is disconnected. Most devices implement Handshake.RequestToSend, they use the RTS and CTS signals to tell the other side that it is ready to receive data and to prevent buffer overflow. Always check the manual first.
Upvotes: 1