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

![跨线程操作无效:控件'textBox1'是从不是在[重复]中创建的线程的线程访问的 跨线程操作无效:控件'textBox1'是从不是在[重复]中创建的线程的线程访问的](http://www.mshxw.com/aiimages/31/371638.png)
