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, avoid开发者_如何学编程ing 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";
}
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;
You should check for the Invoke method.
You should check with InvokeRequired method to see if you are on the same thread or a different thread.
MSDN Reference: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx
Your method can be refactored this way
private void foo() {
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(this.foo));
else
this.Text = "Test";
}
Check - How to: Make Thread-Safe Calls to Windows Forms Controls
private void foo()
{
if (this.InvokeRequired)
{
this.Invoke(() => this.Text = text);
}
else
{
this.Text = text;
}
}
精彩评论