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
2010-07-19 13:06:13
I tried this. But it doesn't work. Can yu give me more details. Thanks in advance!
uhu
2010-07-19 14:47:05
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
2010-07-19 15:27:31
+3
A:
Call the ReportProgress
method from the worker, and handle the ProgressChanged
to update the current state.
Stephen Cleary
2010-07-19 13:08:50
+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
2010-07-19 13:11:05
+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
2010-07-19 13:17:06