我想问一下使用后台工作程序从串口读取数据。是否可以使用一个工作人员从一个串口或更多端口检索数据?我只能在worker中使用一个串口时检索数据。当我使用两个或更多端口时,我无法再检索数据(没有错误消息)。这是我的代码:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
String p = "";
String s = "";
Int32 b = 0;
MethodInvoker get_selectedPort = new MethodInvoker(() =>
{
p = comboBoxPressure.SelectedItem.ToString();
s = comboBoxStrain.SelectedItem.ToString();
b = Convert.ToInt32(comboBoxBaudrate.SelectedItem.ToString());
});
this.Invoke(get_selectedPort);
SerialPort portPressure = new SerialPort(); // serial port 1
portPressure.PortName = p;
portPressure.BaudRate = b;
portPressure.Parity = Parity.None;
portPressure.StopBits = StopBits.One;
portPressure.DataBits = 8;
portPressure.Handshake = Handshake.None;
SerialPort portStrain = new SerialPort(); // serial port 2
portStrain.PortName = s;
portStrain.BaudRate = b;
portStrain.Parity = Parity.None;
portStrain.StopBits = StopBits.One;
portStrain.DataBits = 8;
portStrain.Handshake = Handshake.None;
try
{
portPressure.Open();
portStrain.Open();
}
catch (Exception error)
{
MessageBox.Show("Error while trying open serial port!\r\n" + error.Message, "COM Port Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
worker.CancelAsync();
return;
}
while (!worker.CancellationPending)
{
System.Threading.Thread.Sleep(100);
this.dataPressure = portPressure.ReadExisting();
this.dataStrain = portStrain.ReadExisting();
BeginInvoke((Action)(() => updateData()));
}
portPressure.Close();
portStrain.Close();
}
}