Hello.
I've developed an application that reads at a constant fast rate, bytes from a serial port, and posts these to a textbox on the main form. Basically a serial port monitor of sorts (although the application is for 2-way communication with a specific tool). The tool constantly streams up bytes at a fast rate.
the issue I've run into is I need a better way to put each byte onto the textbox in the main form, without churning up a lot of CPU.
Here's a shortened version of what I'm working with, and I have narrowed down the constant .invoke call as the reason for CPU processing power being used up. Correct me if this is wrong and something else is causing the massive usage of the CPU (right at about 50%).
namespace serialToolComm
{
public partial class Form1 : Form
{
public delegate void delegateSetText(string s);
public Form1()
{
InitializeComponent();
bworker.RunWorkerAsync();
}
private void bworker1_DoWork(object sender, DoWorkEventArgs e)
{
while (serialPort1.IsOpen)
{
if (backgroundWorker1.CancellationPending)
{
Thread.Sleep(100);
e.Cancel = true;
break;
}
else if (serialPort1.BytesToRead > 0)
{
int b = serialPort1.ReadByte();
setText(b.toString() + ", ");
}
else
{ Thread.Sleep(40); }
}
}
private void setText(string s)
{
if (this.textBox1.InvokeRequired)
{
delegateSetText d = new delegateSetText(setText);
this.Invoke(d, new Object[] { s });
}
else
textBox1.AppendText(s);
}
}
}
as you can see and guess this method for use with the delegate is being called rapidly and requiring a lot of CPU usage.