在多线程操作WinForm窗体上的控件时,出现“线程间操作无效:从不是创建控件XXXX的线程访问它”,那是因为微软为了线程安全,窗体上的控件只能通过创建控件的线程来操作控件的数据,也就是只是是UI线程来操作窗体上的控件!
要解决这个问题可以用以下方法:
1、关闭线程安全检查(不过本人不推荐,这种方式可能会发生一些不可预计的后果)
Control对象.CheckForIllegalCrossThreadCalls = false;
2、使用控件的Invoke方法(或BeginInvoke方法、BackgroundWorker)
if (this.InvokeRequired)
{
this.Invoke(new Action(() => button1.Enabled = false));
//button1.Invoke(new MethodInvoker(delegate() { button1.Enabled = false; }));
//textBox1.SafeCall(() =>{ textBox1.Text = (i++).ToString();});
button1.Invoke(new MethodInvoker(() => button1.Enabled = false ));
button1.Invoke(new Action(() => button1.Enabled = false)); // 跨线程访问UI控件
}
else
{
button1.Enabled = false
}
3、使用委托
public delegate void AddLog(string info);
/// <summary>
/// 添加日志
/// </summary>
AddLog OnAddLog;
///

本文介绍了如何在Winform应用程序中安全地跨线程访问UI控件,包括不推荐的关闭线程安全检查,以及推荐使用的控件Invoke方法和委托方法。提供了详细的参考资料。

958

被折叠的 条评论
为什么被折叠?



