自己在写串口通信的时候遇到个这样的问题
自己是用vs2010 c#写的错误提示是这样的“线程间操作无效: 从不是创建控件“txtreceive”的线程访问它。” 用的控件是自带的serialPort
txtreceive是接收区的框
开始的程序是这样写的 表示串口接收到数据后就能触发事件
private void mycomm_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string str = mycomm.ReadExisting().ToString();
txtreceive.Text = txtreceive.Text + str;
}
运行后 用arm给串口发了个数据 提示这个错误 线程间操作无效: 从不是创建控件“txtreceive”的线程访问它。
郁闷 我就没有用线程 怎么会提示这个错误呢~~ 后来在网上查了一下 原来是存在跨线程调用控件的问题
解决方法有两种:第一是加一句话,第二是用委托。因为一句话成功了 我就没有用委托了~
1.解决方法就加了一句话
private void mycomm_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
////////////////////线程开始的时候加这么一句
Control.CheckForIllegalCrossThreadCalls = false;
string str = mycomm.ReadExisting().ToString();
txtreceive.Text = txtreceive.Text + str;
}
ok 程序就运行成功了~
第二:
用委托,在05里,每个控件都有个InvokeRequired的属性~
判断一下是不是true,是的话进行Invoke操作的,完事了~

private delegate void ShowDelegate(string strshow);

public void Show(string strshow)
{
if (this.txtreceive.InvokeRequired)
{
// this.txtreceive.BeginInvoke(new ShowDelegate(Show), strshow);//这个也可以
this.txtreceive.Invoke(new ShowDelegate(Show), strshow);
}
else
{
this.txtreceive.Text += strshow;
}
}
第一种方法只是简单的将错误提示禁用了,仍然存在跨线程调用控件的问题。为此可能造成两个线程同时或者循环改变该控件的状态导致线程死锁。
Invoke方法是同步的方法,所以执行过程是有先后顺序的,所以就不会出现那个异常了 最好是用第二种方法