C#:SerialPort.Open 挂起

问题描述

使用 MS Visual Studio C#。通过 USB 端口循环找到我的设备(具有 USB-SerialPort 仿真的外部微处理器),然后交换 ASCII 数据。 Putty 每次都能正常工作。

经常,当尝试连接到与我的外部设备关联的 USB 端口时,SerialPort1.open() 挂起。我在网上看到了很多关于这个问题的对话,但没有很好的解决方案,我可以找到。我想得到一些更熟悉 VS C# 的人的回应,他们可以提供解决此问题的示例,但这真的很痛苦。

程序好像总是挂在serialPort1.open()上;命令。当不挂断 open() 时,它运行良好。

顺便说一句,添加的 TestSerialPort() 例程是为了解决 open() 问题而添加的。解决问题确实没有多大作用。只是让代码更有趣。 :)

这是我的一些相关代码,我确实使用事件处理程序来处理接收到的文本(未显示):

    private void TestSerialPort(object obj)
    {
        if (!(obj is string))
            return;
        string spName = obj as string;
        SerialPort sp = new SerialPort(spName);
        sp.ReadTimeout = 2000;
        sp.WriteTimeout = 2000;

        try
        {
            sp.open();
        }
        catch (Exception)
        {
            // users don't want to experience this
            return;
        }

        if (sp.IsOpen)
            spReadyFlag = true;

        sp.Close();

    }

    private void Form1_Load(object sender,EventArgs e)
    {
        string[] ports = SerialPort.GetPortNames();
        int numComs;
        int i;

        cboPortList.Items.AddRange(ports);
        numComs = cboPortList.Items.Count;
        if (numComs == 0)
        {
            MessageBox.Show("Please connect the HiFlex product using a USB cable.\n\rOn the HiFlex,use the USB port closest to the power connector.","HiFlex Not Connected");
            System.Environment.Exit(0);
        }

        cboPortList.Selectedindex = 0;

        serialPort1.DataBits = 8;
        serialPort1.StopBits = StopBits.One;
        serialPort1.Parity = Parity.None;
        serialPort1.Handshake = Handshake.None;
        serialPort1.Baudrate = 115200;

        for (i=0; i<numComs; i++)
        {

            try
            {
                spReadyFlag = false;
                Thread t = new Thread(new ParameterizedThreadStart(TestSerialPort));
                t.Start(ports[i]);
                Thread.Sleep(500);
                t.Abort();
                Thread.Sleep(500);

                if (spReadyFlag == false)
                {
                    System.Console.WriteLine($"Unable to Open COM Port: '{ports[i]}'");
                    MessageBox.Show("Serial Port Failed to Open: "+ports[i],"Program Closing.");
                    System.Environment.Exit(0);
                }

                serialPort1.PortName = ports[i];

                serialPort1.open();
                serialPort1.WriteLine("\r");          // Burn first read just in case there is a menu displayed.
                serialPort1.WriteLine("DD\r");        // Burn first read just in case there is a menu displayed.
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"Message",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }

您可能提供的任何帮助将不胜感激。我对 C# 很陌生。我的大部分编程经验是在微处理器编程和位处理方面。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)