gpt4 book ai didi

c# - 传入的串行数据循环导致我的程序卡住

转载 作者:行者123 更新时间:2023-11-30 22:51:28 24 4
gpt4 key购买 nike

我正在编写连接到步进电机串行端口的代码。我通过 textBox2 向步进电机发送命令,并尝试将命令的返回数据读入 textBox3。我能够建立连接、发送命令和接收数据。但是在我的 GUI 用返回的串行数据填充 textBox3 后,它卡住了。

我相信代码会卡在 try 循环 中,但我不知道如何摆脱它。这是我的代码:

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(object sender, 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用于故障排除。

附言这是避免锁定 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;
}));
}

关于c# - 传入的串行数据循环导致我的程序卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59145585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com