Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a Control from a different Thread?

How can I access a control from a thread other than the thread it was created on, avoiding the cross-thread error?

Here is my sample code for this:

private void Form1_Load(object sender, EventArgs e)
{
    Thread t = new Thread(foo);
    t.Start();
}

private  void foo()
{
    this.Text = "Test";
}
like image 688
Thorin Oakenshield Avatar asked Dec 02 '22 03:12

Thorin Oakenshield


1 Answers

There's a well known little pattern for this and it looks like this:

public void SetText(string text) 
{
    if (this.InvokeRequired) 
    {
        this.Invoke(new Action<string>(SetText), text);
    }
    else 
    { 
        this.Text = text;
    }
}

And there's also the quick dirty fix which I don't recommend using other than to test it.

Form.CheckForIllegalCrossThreadCalls = false;
like image 121
John Leidegren Avatar answered Dec 03 '22 19:12

John Leidegren