今天遇到这个问题,把解决的方法总结出来。
在ui线程创建的子线程操作ui控件时,系统提示错误详细信息为:
线程间操作无效: 从不是创建控件“XXX”的线程访问它。
Windows 窗体程序。如果有两个或多个线程操作某一控件的状态,则可能会迫使该控件进入一种不一致的状态。还可能出现其他与线程相关的 bug,包括争用情况和锁死。确保以线程安全方式访问控件非常重要。
以下是解决办法:
1、把CheckForIllegalCrossThreadCalls设置为false
一般会较少的采用此方法,容易造成锁死问题
2、利用委托
private delegate void myDelegate(string str);//声明委托
private Thread thread;
//调用位置,此处使用定时器调用,TimerElapsed为定时器调用方法的名称
private void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
thread = new Thread(new ThreadStart(ThreadProcSafe));
thread.Start();
}
private void ThreadProcSafe()
{
setRich("要调用的数据");
}
private void setRich(string str)
{
//lbLog 控件名
if (this.lbLog.InvokeRequired)
{
myDelegate md = new myDelegate(setRich);
this.Invoke(md, new object[] { str });
}
else
this.txtName.Text=str;
}