可能重复:
Getting Cross-thread operation not valid
Cross-thread operation not valid跨线程操作无效
我试图让我创造新的处理程序以侦听COM端口用于SerialPort.DataReceived事件。逻辑很简单 - 我向TextBox1写东西,按Button1,我的文本应该在Label1中显示它自己。但我的应用程序不想运行,因为它会抛出'跨线程操作无效'错误。 我做了一些搜索并找到了Invoke对象 - 我如何在我的例子中使用它?为什么我需要包含调用逻辑?
namespace WindowsApplication1
{
public partial class Form1 : Form
{
SerialPort sp = new SerialPort();
public Form1()
{
InitializeComponent();
sp.DataReceived += MyDataReceivedHandler;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void MyDataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
try
{
//sp.PortName = "COM3";
//sp.Open();
Label1.Text = sp.ReadLine();
}
catch (Exception exception)
{
RichTextBox1.Text = exception.Message + "\n\n" + exception.Data;
}
finally
{
sp.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
sp.PortName = "COM3";
sp.Open();
sp.WriteLine(TextBox1.Text);
}
catch (Exception exception)
{
RichTextBox1.Text = exception.Message + "\n\n" + exception.Data;
}
finally
{
sp.Close();
}
}
}
}
@ Peter:这里的串口是RS232串口。尽管USB和所有仍然有一些设备(例如GPS,医疗)使用串行端口进行PC通信。 – Sesh 2009-09-04 06:55:49
@_simon_:只是好奇:在这个特定的应用程序中使用的COM端口是什么? – 2009-09-04 07:31:14
@_simon_:我更新了我的答案 – 2009-09-04 09:13:57