线程间操作无效: 从不是创建控件的线程访问它

发布时间:2021-07-13编辑:佚名阅读(988)

在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;
}


  关键字:线程间操作无效从不是创建控件的线程访问它


鼓掌

0

正能量

0

0

呵呵

0


评论区