Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

.net - Detecting when a SerialPort gets disconnected

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

public class SafeSerialPort : SerialPort
{
    private Stream theBaseStream;

    public SafeSerialPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        : base(portName, baudRate, parity, dataBits, stopBits)
    {

    }

    public new void Open()
    {
        try
        {
            base.Open();
            theBaseStream = BaseStream;
            GC.SuppressFinalize(BaseStream);
        }
        catch
        {

        }
    }

    public new void Dispose()
    {
        Dispose(true);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing && (base.Container != null))
        {
            base.Container.Dispose();               
        }
        try
        {
            if (theBaseStream.CanRead)
            {
                theBaseStream.Close();
                GC.ReRegisterForFinalize(theBaseStream);
            }
        }
        catch
        {
            // ignore exception - bug with USB - serial adapters.
        }
        base.Dispose(disposing);
    }
}

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...