可能重複:
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