Visual studio 通过串行端口从 Arduino 接收数据时冻结

Visual studio freezes while receiving data from Arduino through serial port

Visual studio 从Arduino 接收到未知串口数据。我在数据开头发送带有“9594”的数据以获得正确的数据。调试时卡住怎么办?

我用的是Visual Studio2010快递。我可以连续看到文本框中的数据,但是当我开始接收调试的表单时冻结,我无法执行任何其他操作(如单击按钮等)我尝试更改读取数据时间、串行超时等。但程序仍然冻结.

private void button19_Click(object sender, EventArgs e)
    { 
        while (true)
        {
            try
            {
                string x = serialPort1.ReadLine();


                if (x.IndexOf("9594") >= 0)
                {

                    x = x.Remove(0, 4);           
                    double y = double.Parse(x); 
                    string z = textBox10.Text;
                    double zd = double.Parse(z);
                    textBox12.Text = x;
                    if (y < zd)
                    {

                        power_limit_turn_off_plugs();

                    }
                    else if (y > zd)
                    {
                        turn_to_last_state_of_plugs();
                    }
                }
            }

            catch (TimeoutException)
            { }
        }
}

串行输出就像(Arduino 端):

95940.00
95940.00
95945.51
95945.51
95948.93
95948.93
95945.51

这是预料之中的,因为您正在用无限的 while 循环阻塞 UI 线程。您应该在不同的线程中执行较长的 运行 任务。

请记住,一旦您尝试从另一个线程访问表单控件,您将遇到 InvalidOperationException

这个post解释了很多。 https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls

只需在开始时设置 CheckForIllegalCrossThreadCalls = false,然后当您了解更多信息时,按照上面 link 中解释的正确修复。