Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

c# - Accessing a form's control from a separate thread

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...