Access to a control from a separate thread

I am engaged in carving and have come across this problem. The situation is as follows:

  • I have 4 progress bars in one form, one for loading a file, one for displaying page load status, etc.

  • I need to control the progress of each ProgressBar from a separate thread.

The problem is that I get an InvalidOperationException which says

Work with cross-streams is invalid: the control "progressBar1" is accessible from the thread, except for the thread on which it was created.

Am I mistaken in this approach, or can someone tell me how to implement this?

+8
multithreading c # winforms
source share
5 answers

User interface elements can only be accessed through the user interface stream. WinForms and WPF / Silverlight do not allow access to controls from multiple threads.

A workaround for this limitation can be found here .

+9
source share

A Control can only be accessed in the thread that created it, in the user interface thread.

You would need to do something like:

 Invoke(new Action(() => { progressBar1.Value = newValue; })); 

The invoke method then executes the specified delegate in the user interface thread.

+30
source share

You can check the Control.InvokeRequired flag, and then use Control.Invoke if necessary. Control.Invoke accepts a delegate, so you can use the built-in Action <T>.

 public void UpdateProgress(int percentComplete) { if (!InvokeRequired) { ProgressBar.Value = percentComplete; } else { Invoke(new Action<int>(UpdateProgress), percentComplete); } } 
+9
source share
  private void Form1_Load(object sender, EventArgs e) { CheckForIllegalCrossThreadCalls = false; } 

Maybe it will work.

+5
source share

You need to call the Invoke method from threads other than the UI to perform some actions on the form and other controls.

+2
source share

All Articles