栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

跨线程操作无效:控件'textBox1'是从不是在[重复]中创建的线程的线程访问的

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

跨线程操作无效:控件'textBox1'是从不是在[重复]中创建的线程的线程访问的

您的

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

因此,不要直接在

serialport1_DataReceived
方法中设置text属性,而是使用以下模式:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/371638.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号