简体   繁体   English

通过 com 端口循环

[英]Looping through com ports

I am writing an application that will loop through my computer's com ports.我正在编写一个应用程序,它将循环通过我计算机的 com 端口。 The issue I am having is one of the com ports is opened on PC startup by another process which causes an exception to be thrown:我遇到的问题是 com 端口之一在 PC 启动时被另一个进程打开,这会导致引发异常:

System.InvalidOperationException: 'The port is already open.' System.InvalidOperationException: '端口已经打开。'

I have successfully handled the exception but it seems to break the foreach loop once it hits the exception and will not continue to the other ports.我已经成功处理了异常,但是一旦遇到异常,它似乎会中断foreach循环,并且不会继续到其他端口。 Am I handling the expectation correctly by having the try catch block inside of the foreach loop?我是否通过在 foreach 循环中使用 try catch 块来正确处理期望?

private void Rescan()
{
    bool error = false;
    int baud = 115200;
            
    string[] ports = SerialPort.GetPortNames();

    foreach (string port in ports)
    {

        try
        {
            comPort.PortName = port;
            comPort.BaudRate = baud;      //convert Text to Integer
            comPort.Open();
            comPort.DtrEnable = true;
            comPort.DataReceived += SerialPortDataReceived;
                        
            System.Windows.MessageBox.Show(port.ToString());
        }
        catch (InvalidOperationException e)
        {
            System.Windows.MessageBox.Show("");
        }
                    
    }
}

I know it can be dangerous and poor programing practice to open ALL com ports that are not mine, so my end goal is to open each com port and write some string like "ID_DEVICE" which will then prompt a response from the firmware of the device I am trying to connect to (Arduino).我知道打开所有不属于我的 com 端口可能是危险且糟糕的编程实践,所以我的最终目标是打开每个 com 端口并编写一些字符串,例如“ID_DEVICE”,然后会提示设备固件的响应我正在尝试连接到(Arduino)。 If the com port does not have a proper response then my application will close that specific port and only leave open the ports that had the proper response.如果 com 端口没有正确响应,那么我的应用程序将关闭该特定端口,只打开具有正确响应的端口。

I think John is right, you have to instanciate a new serial port for each port name.我认为约翰是对的,您必须为每个端口名称实例化一个新的串行端口。 If you register an event, don't forget to unsubscribe.如果您注册了活动,请不要忘记取消订阅。 Fe you can store the open comports in an collection to be able to close, deregister the event and dispose the serial port.您可以将打开的 comport 存储在一个集合中,以便能够关闭、取消注册事件并处理串行端口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM