【发布时间】:2019-03-24 13:27:18
【问题描述】:
我是 C# 新手,正在寻找一些关于我一直试图在我的 Windows 窗体应用程序中解决的问题的建议。
我有一个应用程序需要连续读取通过连接的串行端口返回到程序的数据。我有通过用户打开和关闭端口的按钮。我在配置“DataReceived”事件处理程序以读取传入数据并将其显示在应用程序的文本框中时遇到问题。
我收到此错误:“跨线程操作无效:控件'textBox4'从创建它的线程以外的线程访问。”我看到这是一个线程错误,但我无法弄清楚我的问题。
namespace Program
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getAvailabePorts();
}
private void getAvailabePorts()
{
String[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
public void button1_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || comboBox2.Text == "")
{
textBox4.Text = "Please select port settings";
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
serialPort1.Open();
}
}
catch (UnauthorizedAccessException)
{
textBox4.Text = "Unauthorized Access";
}
public void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
textBox4.Text = sp.ReadExisting() + "\n";
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();
textBox4.Clear();
}
}
}
}
【问题讨论】:
-
串行端口的事件处理程序无法更新表单 UI,因为它在单独的线程中运行。您需要使用委托。阅读此内容,了解如何操作...stackoverflow.com/a/17810763/3516555
标签: c# multithreading winforms events serial-port