我正在尝试监听COM端口,以便为SerialPort.DataReceived事件创建新的处理程序。逻辑很简单-我在TextBox1中写入一些内容,按下Button1,我的文本应该显示在Label1中。但是我的应用程序不想运行,因为它会抛出“跨线程操作无效”的错误。
我进行了一些搜索,并找到了Invoke对象-我如何在我的示例中使用它?为什么需要包含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();
}
}
}
}