Read data from multiple serial port
Hi guys, i want to ask about read data from serial port using background worker. Is it possible to retrieve data from one serial port or more using one worker? I can retrieve data when only use one serial port in worker. When i use two or more ports, i can't retrieve data anymore (without error message). Here is my code :
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();
}