问题
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";
}
回答1:
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;
回答2:
You should check for the Invoke method.
回答3:
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";
}
回答4:
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;
}
}
来源:https://stackoverflow.com/questions/5243333/how-to-access-a-control-from-a-different-thread