如何从不同的线程访问控件? [英] 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?
这是我的示例代码:
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;
这篇关于如何从不同的线程访问控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文