Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a form's control from a separate thread

Tags:

I'm practising on threading and came across this problem. The situation is like this:

  1. I have 4 progress bars on a single form, one for downloading a file, one for showing the page loading status etc...

  2. I have to control the progress of each ProgressBar from a separate thread.

The problem is I'm getting an InvalidOperationException which says

Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on.

Am I wrong in this approach or can anybody tell me how to implement this?

like image 591
Chandra Eskay Avatar asked Sep 30 '11 11:09

Chandra Eskay


People also ask

What is cross threading in C#?

In the first line we get to know whether the control we want to access is created on the same thread or another thread. If it's created on another thread then it will execute the second line.

Why use InvokeRequired in c#?

Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on.


1 Answers

A Control can only be accessed within the thread that created it - the UI thread.

You would have to do something like:

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

The invoke method then executes the given delegate, on the UI thread.

like image 180
ebb Avatar answered Sep 18 '22 13:09

ebb