By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,952 Members | 1,570 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,952 IT Pros & Developers. It's quick & easy.

need a better way to post data from background thread to main thread

P: 14
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.
Jun 23 '08 #1
Share this Question
Share on Google+
1 Reply


Plater
Expert 5K+
P: 7,872
Don't post each byte at a time, wait till you have a few available and then post them? Just waiting for 2 bytes instead of every one will cut your usage in like half
Jun 23 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.