我正在使用 C# 和 Arduino 开发一个应用程序。我从 Arduino 读取值并在文本框上设置值。我想始终从 Arduino 读取值并在界面上设置它。但是这段代码不起作用。 我应该在不同的线程中运行 while 语句吗?
这是我的代码
SerialPort port = new SerialPort("COM4", 9600);
port.Open();
while (true)
{
String s=port.ReadLine();
txtValue.Text=s;
}
port.Close();
}
我想显示我从 Arduino 读取的值同时显示在文本框中。
请您参考如下方法:
这是开始的代码(将它放在构造函数、窗口 Loaded 或按钮单击事件中):
Task.Run(() =>
{
_stop = false; // define as private field of window class
var port = new SerialPort("COM4", 9600);
port.Open();
while (!_stop)
{
var s=port.ReadLine();
Dispatcher.Invoke(() => txtValue.Text = s); // InvokeAsync?
}
port.Close();
});
这是停止的代码(将其放入窗口 Closing 事件):
_stop = true;
这不使用任何绑定(bind),但应该让您了解如何组织端口操作(有或没有绑定(bind))。
