1st off I am not even sure what a C# Cross-Thread Operation
is, so seeing this debug message blows my mind from the start - Cross-thread operation not valid: Control 'panel1' accessed from a thread other than the thread it was created on.
I am just attempting to write to a textbox to show the progress of my procedures. Thread.Sleep()
is used in the code below for brevity. I receive the debug message when my code hits the line panel1.Controls.Add(txt);
And here is full code:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private DateTime now = DateTime.Now;
private int i = 0;
TextBox txt = new TextBox();
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = false;
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
panel1.Controls.Add(txt);
MethodOne();
MethodTwo();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void MethodOne()
{
txt.Text = "MethodOne Process Has Begun....." + now;
Thread.Sleep(100);
txt.Text = "MethodOne Process Has Finished....." + now;
}
private void MethodTwo()
{
txt.Text = "MethodTwo Process Has Begun....." + now;
Thread.Sleep(100);
txt.Text = "MethodTwo Has Finished....." + now;
}
}
}
Please let me know if I need to provide any further details or more information about how my windows form is set-up.