当的SerialPort断开连接检测SerialPort

2023-09-02 10:51:24 作者:亡心率

我有一个开放的SerialPort 并通过 DataReceived 事件接收数据。

I have an open SerialPort and receive data through the DataReceived event.

有什么方法来检测是否的SerialPort 断开连接?

Is there any way to detect if the SerialPort gets disconnected?

我试过 ErrorReceived PinChanged 事件,但没有运气。

I tried the ErrorReceived and PinChanged events but no luck.

除此之外, SerialPort.IsOpen 返回true时的物理连接。

In addition to that, SerialPort.IsOpen returns true when physically disconnected.

推荐答案

USB串行端口是一个巨大疼痛。参见,例如,这个问题。我不知道是否真的是固定与.NET 4.0,但早在一天,我试图解决断线像这样轰然整个程序的问题:

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);
    }
}

道歉谁我适应这个从,看来我没能记下它在我的code。问题显然是从如何.NET在串行端口消失的情况下,处理的基础流源于。这似乎后串行端口断开你不能关闭该流。

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.

另一种策略,我用的是创建一个小程序,就是这样做的串行通信部分和我的主要程序连接到暴露WCF服务。这样一来,当USB串口适配器片出来,崩溃通信程序,我可以自动从我的主要程序重新启动。

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.

最后,我不知道为什么从来没有人销售的锁定USB端口,以避免整个意外断开的问题,特别是USB转串口适配器!

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!

相关推荐