views:

76

answers:

4

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 ?

+2  A: 

Check if invoke is required, then call BeginInvoke.

private void AdjustControls()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(this.AdjustControls));
            }
            else
            {
                label1.Text = "Whatever";
            }
        }
Kurt
I tried this. But it doesn't work. Can yu give me more details. Thanks in advance!
uhu
Sorry my bad, I fixed it up a bit. If AdjustControls takes parameters, for example, if it is an event handler, then you cannot use MethodInvoker, you have to define a delegate for it.
Kurt
+3  A: 

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

Stephen Cleary
+1  A: 

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.

Dan Tao
+1  A: 

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
Joel Kennedy