Detecting when a SerialPort gets disconnected

后端 未结 7 993
天命终不由人
天命终不由人 2020-12-01 09:25

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

Is there any way to detect if the SerialPort gets d

7条回答
  •  难免孤独
    2020-12-01 10:17

    I also faced the problem of an unhandleable exception (and not being able to detect/circumvent the problem in code) as soon as the USB-Serial adapter had been disconnected. I can confirm that the solution from Mattt Burland works.

    Simplified version:

    class SafeSerialPort : SerialPort {
        public new void Open() {
            if (!base.IsOpen) {
                base.Open();
                GC.SuppressFinalize(this.BaseStream);
            }
        }
    
        public new void Close() {
            if (base.IsOpen) {
                GC.ReRegisterForFinalize(this.BaseStream);
                base.Close();   
            }           
        }
    
        protected override void Dispose(bool disposing) {
            try {
                base.Dispose(disposing);
            } catch (Exception ex) {
                Debug.WriteLine(ex.Message);
            }
    
        }
    }
    

提交回复
热议问题