传入的串行数据循环导致我的程序冻结

Incoming serial data loop is causing my program to freeze

我正在编写连接到步进电机串行端口的代码。我通过 textBox2 向步进电机发送命令,并试图从命令中读取 return 数据到 textBox3。我能够建立连接、发送命令和接收数据。但是在我的 GUI 用 returned 串行数据填充 textBox3 后,它冻结了。

我认为代码卡在 try loop 中,但我不知道如何摆脱它。这是我的代码:

private void button3_Click(object sender, EventArgs e)
{
    if (isConnectedMotor)
    {
        string command = textBox2.Text;
        portMotor.Write(command + "\r\n");
        portMotor.DiscardInBuffer();

        while (true)
        {
            try
            {
                string return_data = portMotor.ReadLine();
                textBox3.AppendText(return_data);
                textBox3.AppendText(Environment.NewLine);
            }
            catch(TimeoutException)
            {
                break;
            }
        }       
    }
}

数据接收代码:

private void connectToMotor()
{
    isConnectedMotor = true;
    string selectedPort = comboBox2.GetItemText(comboBox2.SelectedItem);
    portMotor = new SerialPort(selectedPort, 9600, Parity.None, 8, StopBits.One);
    portMotor.RtsEnable = true;
    portMotor.DtrEnable = true;
    portMotor.Open();
    portMotor.DiscardInBuffer();
    portMotor.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
    button4.Text = "Disconnect";
    enableControlsMotor();
}

private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();
    textBox3.AppendText(indata);
    textBox3.AppendText(Environment.NewLine);
}

我收到一条错误消息:

An object reference is required for the non-static field, method, or property 'Form1.textBox3'

调用代码:

private void DataReceivedHandler(对象发送者,SerialDataReceivedEventArgs e) {

        portMotor.DiscardInBuffer();
        incoming_data = portMotor.ReadExisting();
        this.Invoke(new EventHandler(displayText));
    }

    private void displayText(object o, EventArgs e)
    {
        textBox3.Text += incoming_data;
    }

不要循环读取数据,而是使用 DataReceived 事件异步获取传入字节。

documentation and example。 另请参阅 this question 进行故障排除。

P.S。这是避免锁定 UI.

的代码示例
private void ReceivedHandler(object sender, SerialDataReceivedEventArgs e) {
    var incoming_data = portMotor.ReadExisting();

    // this is executing on a separate thread - so throw it on the UI thread
    Invoke(new Action(() => {
        textBox3.Text += incoming_data;
    }));
}