How can I do to access an element from another thread? In the case, I have a richtextbox in the Main Thread (GUI), and I'm running a method on a secondary thread. I want to access the richeditbox through the secondary thread
private void Log(string input, Label lbl)
{
lbl.Invoke(new Action(()=>
{
lbl.Text = "Status: " + input;
Thread.Sleep(50);
}));
}
void Run()
{
foreach (string line in richTextBox1.Lines)
{
Log(line, label1);
Thread.Sleep(500);
}
}
private void button1_Click(object sender, EventArgs e)
{
ThreadStart th = new ThreadStart(() => Run());
Thread th2 = new Thread(th);
th2.Start();
//th2.Join();
}
The following error is shown:
Invalid thread operation: control 'richTextBox1' accessed from a thread that is not the one in which it was created.