跨线程操作无效:控制“textBox1"从创建它的线程以外的线程访问 [英] Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

查看:41
本文介绍了跨线程操作无效:控制“textBox1"从创建它的线程以外的线程访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 UART 将温度值从微控制器发送到 C# 接口并在 Label.Content 上显示温度.这是我的微控制器代码:

I want to send temperature value from a microcontroller using UART to C# interface and Display temperature on Label.Content. Here is my microcontroller code:

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'从一个线程访问,而不是在创建它的线程"请告诉我如何从我的微控制器获取温度字符串并消除此错误!

but exception arises there "Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on" Please tell me how to get temperature string from my microcontroller and remove this Error!

推荐答案

在您的 serialPort1_DataReceived 方法中接收的数据来自另一个线程上下文而不是 UI 线程,这就是您看到此错误的原因.
要解决此问题,您必须使用 MSDN 文章中所述的调度程序:
如何至:对 Windows 窗体控件进行线程安全调用

The data received in your serialPort1_DataReceived method is coming from another thread context than the UI thread, and that's the reason you see this error.
To remedy this, you will have to use a dispatcher as descibed in the MSDN article:
How to: Make Thread-Safe Calls to Windows Forms Controls

因此不要直接在 serialport1_DataReceived 方法中设置 text 属性,而是使用此模式:

So instead of setting the text property directly in the serialport1_DataReceived method, use this pattern:

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());
}

这篇关于跨线程操作无效:控制“textBox1"从创建它的线程以外的线程访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆