?
Solved

Threading a form control

Posted on 2009-04-30
9
Medium Priority
?
360 Views
Last Modified: 2013-12-17
My code executes a command prompt and reads the results. My problem is when I add a new line to a ritchtextbox the control locks up until the thread is finished. I understand why this occurs but can't figure out how to thread  appropriately. I keep running into an error that states I can't update the form's control from an outside thread. I've attempted to fix it but failed every time.
private void button2_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            Process scanProcess = new Process();
            scanProcess.StartInfo.RedirectStandardError = true;
            scanProcess.StartInfo.RedirectStandardOutput = true;
            scanProcess.StartInfo.UseShellExecute = false;
            scanProcess.StartInfo.FileName = "cmd.exe";
            scanProcess.StartInfo.Arguments = "/c " + comboBox1.SelectedItem + " " + textBox1.Text;
            scanProcess.StartInfo.CreateNoWindow = true;
            scanProcess.Start();
 
            StreamReader sOut = scanProcess.StandardOutput;
            StringBuilder result = new StringBuilder();
            string temp;
 
            while ((temp = sOut.ReadLine()) != null)
                richTextBox1.Text += temp + Environment.NewLine;
 
            sOut = scanProcess.StandardError;
 
            while ((temp = sOut.ReadLine()) != null)
                result.AppendLine(temp);
 
            sOut.Close();
            scanProcess.Close();
        }

Open in new window

0
Comment
Question by:drilus
  • 4
  • 3
  • 2
9 Comments
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 1000 total points
ID: 24273972
I do not see any threads in your code. You may want to use a BackGroundWorker control instead of thread because its easy to update UI.
0
 
LVL 5

Author Comment

by:drilus
ID: 24274082
I didn't post my thread code simple because it didn't work with updating form controls. I'll give the BackGroundWorker control some looking into. Thanks.
0
 
LVL 23

Expert Comment

by:Tony McCreath
ID: 24277522
your while loops are in the Main GUI thread. Your GUI will lock up until they finish.

You need to place that monitoring code in another thread, like a BackGroundWorker.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 5

Author Comment

by:drilus
ID: 24278433
"Cross-thread operation not valid: Control 'comboBox1' accessed from a thread other than the thread it was created on."

I know I have to use invoke. This is the exact same problem I ran into when creating a thread. How do I update a control using invoke?
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 24278485
0
 
LVL 23

Assisted Solution

by:Tony McCreath
Tony McCreath earned 1000 total points
ID: 24278548
The code snippet shows the pattern I follow.

Have the thread call methods like this to trigger the GUI to update its display. E.g. after each line is read.

You can create your own EventArgs class to pass information from the thread, or use your own deligate to change the parameters it accepts or even share data via properties in the class.
public void WorkerProgressedEvent(object sender, EventArgs e)
{
	if (this.InvokeRequired)
	{
		this.Invoke(new EventHandler(this.WorkerProgressedEvent), new object[] { sender, e });
	}
	else
	{
		// update the GUI
	}
}

Open in new window

0
 
LVL 5

Author Comment

by:drilus
ID: 24278996
Oh, well I was just able to get Invoke to work in the BackgroundWorker. lol
Is the code I'm using safe?
            while ((temp = sOut.ReadLine()) != null)
                richTextBox1.Invoke((MethodInvoker)delegate()
                {
                    richTextBox1.Text += temp + Environment.NewLine;
                });

Open in new window

0
 
LVL 23

Expert Comment

by:Tony McCreath
ID: 24279294
That looks fine. as you know an invoke is required you don't need to do the check.
0
 
LVL 5

Author Closing Comment

by:drilus
ID: 31576498
Thanks for helping me guys. This was bugging me.  =]
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question