开发者

How to solve the "Cross-thread operation not valid" Problem?

开发者 https://www.devze.com 2023-01-07 17:30 出处:网络
I have a windows forms dialog, where a longer operation is running (asynchron) within a backgroundworker job. During this operation I want to change some values on the form (labels,...). But when the

I have a windows forms dialog, where a longer operation is running (asynchron) within a backgroundworker job. During this operation I want to change some values on the form (labels,...). But when the backgroundworker tries to change something on the form, I get t开发者_如何学Pythonhe error "Cross-thread operation not valid"! How can this problem be solved ?


Call the ReportProgress method from the worker, and handle the ProgressChanged to update the current state.


Check if invoke is required, then call BeginInvoke.

private void AdjustControls()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(this.AdjustControls));
            }
            else
            {
                label1.Text = "Whatever";
            }
        }


I feel a little weird tooting my own horn here, but you may find some use from the ThreadSafeControls library I wrote for exactly this purpose.


You cannot change controls directly inside a thread which did not create them. You can use an invoke method as shown above, or you can use the BackgroundWorker ProgressChanged event.

Code used inside BackgroundWorker DoWork:

myBackgroundWorker.ReportProgress(50); // Report that the background worker has got to 50% of completing its operations.

Code used inside BackgroundWorker ProgressChanged:

progressBar1.Value = e.ProgressPercentage; // Change a progressbar on the WinForm
0

精彩评论

暂无评论...
验证码 换一张
取 消