I am receiving data from a serial port, placing each line into a queue and then de-queuing the lines, formatting them slightly (removing some leading characters, trimming etc), and then displaying the formatted lines in a listbox.
I am using a Timer to fire the Dequeuing method every 200ms. Everything is working but it seems to be a bit sluggish/slow.
I am considering using a BackgroundWorker to handle the de-queuing and formatting but im getting stuck.
I tried to start the backgroundworker in FormLoad, but quickly realized it would run through the code only once. I tried a label and goto inside the backgroundworker code to create a loop (i know, not good) but that got me high CPU usage and didnt even work.
I also tried using " backgroundWorker1.RunWorkerAsync(); " in my serial received event to run it every time new data comes in but that throws the 'Background worker currently busy" exception
So, I need the background worker to continuously process the queue (dequeue).
Code: heres my data received event, and below that my dequeuing code thats sitting in the backgroundworker. Any help much appreciated.
// Serial Data Received
private void serialPort1_DataReceived(
object sender,
System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadTo("\u0003");
q.Enqueue(RxString);
}
Next Code is the dequeue code:
// Dequeue items, format, then display in listbox
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (q.Count == 0)
{
// do nothing if q is empty
}
else
do
{
output = (q.Dequeue().ToString());
output = output.TrimStart(new char[] { (char)02 });
output = output.TrimEnd(new char[] { (char)03 });
if (output.StartsWith("C"))
{
ClearAll();
}
else if (output.StartsWith("W98"))
{
txtTax.Text = (output.Remove(0, 5));
}
else if (output.StartsWith("W99"))
{
txtTotal.Text = (output.Remove(0, 24));
}
else
{
listOrderItems.Items.Add(output.Remove(0, 5));
listOrderItems.SelectedIndex = listOrderItems.Items.Count - 1;
}
} while (q.Count > 0);
}