I'm new to C# and GUI development in general. Please if this is an old question, just direct me to that source and I will take down this question.
My Situation: So I'm writing a GUI that redirects Console output of one function to a text box in my Windows Application Form. The Console output just displays information to the user like serial number of device, current software version, etc.
My Problem: This form works great, except that the process of updating the software takes a couple of minutes which freezes up my form until it is complete. Now, I know that implementing a background worker will alleviate this problem. However, when I implement the background worker I receive the following error.
Cross-thread operation not valid: Control 'TextBox' accessed from a thread other than the thread it was created on.
A summary of my code is as follows:
public class Form1 : Form
{
this.backgroundWorker1.DoWork += new
System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
BigProcess(bw);
}
private void BigProcess(BackgroundWorker bw)
{
// lengthy operation that includes lots of
Console.WriteLine("feedback stuff for the user");
}
private void button1_Click(object sender, EventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();
}
}
In this project I also have a class TextBoxStreamWriter
derived from StringWriter
which is taking care of the redirecting of console output for me. In TextBoxStreamWriter
I am overriding the WriteLine
methods and the Write
method.
Here is an example of what I am doing:
public override void WriteLine(string value)
{
base.WriteLine(DateTime.Now.ToString(value));
textBoxOutput.AppendText(value.ToString() + Environment.NewLine);
writer.Write(value);
}
An InvalidOperationException is thrown when this method is called.
How can I make this thread-safe? Any help would be appreciated.