如何解决“跨线程操作无效”问题问题?

我有一个Windows窗体对话框,其中较长的操作在backgroundworker作业中运行(异步)。在此操作期间,我想更改表单上的一些值(标签,...)。但是当backgroundworker尝试更改表单上的某些内容时,我收到错误“跨线程操作无效”!怎样才能解决这个问题?     
已邀请:
从worker调用
ReportProgress
方法,并处理
ProgressChanged
以更新当前状态。     
检查是否需要调用,然后调用BeginInvoke。
private void AdjustControls()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(this.AdjustControls));
            }
            else
            {
                label1.Text = "Whatever";
            }
        }
    
我觉得这里有一点奇怪,但是你可能会从我为此目的编写的ThreadSafeControls库中找到一些用处。     
您无法直接在未创建它们的线程内更改控件。您可以使用如上所示的invoke方法,也可以使用BackgroundWorker ProgressChanged事件。 BackgroundWorker DoWork中使用的代码:
myBackgroundWorker.ReportProgress(50); // Report that the background worker has got to 50% of completing its operations.
BackgroundWorker ProgressChanged中使用的代码:
progressBar1.Value = e.ProgressPercentage; // Change a progressbar on the WinForm
    

要回复问题请先登录注册