如何从创建它的线程以外的线程访问控件,避免跨线程错误?
这是我的示例代码:
private void Form1_Load(object sender, EventArgs e)
{
Thread t = new Thread(foo);
t.Start();
}
private void foo()
{
this.Text = "Test";
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*ren 12
有一个众所周知的小模式,它看起来像这样:
public void SetText(string text)
{
if (this.InvokeRequired)
{
this.Invoke(new Action<string>(SetText), text);
}
else
{
this.Text = text;
}
}
Run Code Online (Sandbox Code Playgroud)
还有快速的脏修复,除了测试之外,我不推荐使用它.
Form.CheckForIllegalCrossThreadCalls = false;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7277 次 |
| 最近记录: |