uhu
uhu

Reputation: 1742

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

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 the error "Cross-thread operation not valid"! How can this problem be solved ?

Upvotes: 1

Views: 609

Answers (4)

Kurt
Kurt

Reputation: 4517

Check if invoke is required, then call BeginInvoke.

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

Upvotes: 2

Joel Kennedy
Joel Kennedy

Reputation: 1611

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

Upvotes: 1

Dan Tao
Dan Tao

Reputation: 128317

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.

Upvotes: 1

Stephen Cleary
Stephen Cleary

Reputation: 456417

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

Upvotes: 3

Related Questions