468,733 Members | 2,304 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,733 developers. It's quick & easy.

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


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()

private void bworker1_DoWork(object sender, DoWorkEventArgs e)
while (serialPort1.IsOpen)
if (backgroundWorker1.CancellationPending)
e.Cancel = true;
else if (serialPort1.BytesToRead > 0)
int b = serialPort1.ReadByte();
setText(b.toString() + ", ");
{ Thread.Sleep(40); }

private void setText(string s)
if (this.textBox1.InvokeRequired)
delegateSetText d = new delegateSetText(setText);
this.Invoke(d, new Object[] { 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
1 840
7,872 Expert 4TB
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.

Similar topics

10 posts views Thread by Cool Guy | last post: by
1 post views Thread by Srinivasa Ra via .NET 247 | last post: by
10 posts views Thread by Paul | last post: by
4 posts views Thread by dsimmons | last post: by
2 posts views Thread by xarzu | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.