Detecting when a SerialPort gets disconnected

后端 未结 7 985
天命终不由人
天命终不由人 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:22

    I solved this problem with a simple backgroundworker. I continuously check/set all current ports into an array and if new ports are different to my ports-array I get the changed ports from these 2 arrays.

    Example:

    // global variable
    List<string> oldPorts = new List<string>();    // contains all connected serial ports
    
    private void bgw_checkSerialPorts_DoWork(object seder, DoWorkEventArgs e)
    {
        while (true)
        {
            string[] currentPorts = SerialPort.GetPortNames();    // get all connected serial ports
            string[] diffPorts = currentPorts.Except(oldPorts.ToArray());    // get the differences between currentPorts[] and oldPorts-list
    
            if (diffPorts.Length > 0)
            {
                // iterate all changed ports
                for (int i = 0; i < diff.Length; i++)
                {
                    // check if changed port was in old list
                    if (oldPorts.Contains(diff[i]))
                    {
                        // port in diff[] was removed
                    }
                    else
                    {
                        // port in diff[] is a new device
                    }
                }
            }
    
            oldPorts = currentPorts.ToList();   // update oldPortlist
    
            // check every 100ms
            Thread.Sleep(100);
        }
    }
    
    0 讨论(0)
提交回复
热议问题