0

Basic Goal is that i have four progress bar and want to run them at once as button is pressed and i donot have to use background worker have to do by this.

 var t = new Thread(() => { try { } }); t.SetApartmentState(ApartmentState.STA); t.Start(); 

I tried and codded

 for (i = 0; i < 4; i++) { var t = new Thread(() => { for (double x = 0; x < 10000; x = x + 0.5) { progressVal=(int)x; this.Invoke(new EventHandler(ProgressBar)); Thread.Sleep(2); } }); t.SetApartmentState(ApartmentState.STA); t.Start(); } private void ProgressBar(object sender, EventArgs e) { progressBar1.Value=progressVal; } 

but cannot think of idea how to manuplate other progress bars

5
  • 1
    Use the thread pool for that to avoid paying the significant overhead of spawning new threads all the time. Commented Jan 2, 2011 at 19:03
  • 4
    Sorry, but all telepaths have day-off today. Could you please clarify your statement and what is a question here? Commented Jan 2, 2011 at 19:04
  • 1
    ...and i donot have to use background worker... Is this homework? Commented Jan 2, 2011 at 19:23
  • A BackgroundWorker is far more adapted to your scenario unless there's something else you forgot to mention. Commented Jan 2, 2011 at 19:30
  • no it was discussion among friends some beilve that this is not possible so it was kind of chalange Commented Jan 2, 2011 at 19:32

1 Answer 1

4

I would put the progress bars into an array:

var pBars = new[] { progressBar1, progressBar2, progressBar3, progressBar4 }; foreach (var pBar in pBars) { new Thread(currentPBar => { for (double x = 0; x < 10000; x = x + 0.5) { var progress = (int)x; Action<ProgressBar, int> del = UpdateProgress; Invoke( del, new object[] { (ProgressBar)currentPBar, progress } ); Thread.Sleep(2); } }).Start(pBar); } 

and the UpdateProgress method:

private void UpdateProgress(ProgressBar pBar, int progress) { pBar.Value = progress; } 

This being said, using a BackgroundWorker is far more adapted to your scenario.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you.One more Do background woeker implements something like this at backend?
@Afnan, BackgroundWorker uses threads drawn from the thread pool which are reused. You don't need to manually create and start threads. It also takes care of properly marshaling calls between the main GUI thread and the worker thread so that you don't have to manually call the Invoke method. It also makes your code more concise and readable.
In your code Invoke( UpdateProgress, new object[] { (ProgressBar)currentPBar, progress } was not working Error is The best overloaded method match for 'System.Windows.Forms.Control.Invoke(System.Delegate, params object[])' has some invalid arguments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.