我想使用 UART 将温度值从微控制器发送到 C# 接口并显示温度Label.Content
。这是我的微控制器代码:
while(1) {
key_scan(); // get value of temp
if (Usart_Data_Ready())
{
while(temperature[i]!=0)
{
if(temperature[i]!=' ')
{
Usart_Write(temperature[i]);
Delay_ms(1000);
}
i = i + 1;
}
i =0;
Delay_ms(2000);
}
}
我的 C# 代码是:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
txt += serialPort1.ReadExisting().ToString();
textBox1.Text = txt.ToString();
}
但那里出现例外“跨线程操作无效:从创建它的线程以外的线程访问控制“textBox1””
请告诉我如何从我的微控制器获取温度字符串并消除此错误!
您收到的数据serialPort1_DataReceived
方法来自 UI 线程之外的另一个线程上下文,这就是您看到此错误的原因。
要解决此问题,您必须使用 MSDN 文章中所述的调度程序:
如何:对 Windows 窗体控件进行线程安全调用 https://learn.microsoft.com/dotnet/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls
因此,不要直接在serialport1_DataReceived
方法,使用此模式:
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
所以在你的情况下:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
txt += serialPort1.ReadExisting().ToString();
SetText(txt.ToString());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)