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

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

问题描述

我想从使用UART到C#接口和显示温度的微控制器上的 Label.Content 发送温度值。这里是我的微控制器code:

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#code是:

and my C# code is:

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线程另一个线程的上下文来了,这就是之所以出现此错误。结果
为了解决这个问题,你将不得不使用调度作为descibed 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 方法直接设置文本属性,请使用以下模式:

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天全站免登陆