Jack
Jack

Reputation: 16724

How to get a progress value provided by a BackgroundWorker?

Is there something like this on BackgroundWorker? when a function ends in DoWork callback, I get it on ProgressChanged a value of this progress according with the functions are ending.

Code example:

bw.DoWork += (a,b) => {
  foo();
  baa();
  if(..) else {  }
};

when each statement ends, I get it on

  bw.ProgressChanged += (o, e) => {
                   MessageBox.Show(e.ProgressPercentage);
   };

I have three stataments, it should print three Message.Show(): 33,66,100

33% => foo() was executed.

66% => baa() was executed.

100% => if(..) else { } the last statement was executed, done.

I could to call .ReportProgress() method inside each function/statement that run on DoWork callback event,but depending of statements numbers,this can be inviable.

I hope this is clear. And my apologies for my bad english.

Upvotes: 0

Views: 162

Answers (2)

Servy
Servy

Reputation: 203829

Is there a problem with the following approach?

bw.DoWork += (a,b) => {
  foo();
  bw.ReportProgress(33);
  baa();
  bw.ReportProgress(66);
  if(..) else {  }
  bw.ReportProgress(100);
};

I would only try and call ReportProgress inside of foo or baa if there was some compelling reason to (i.e. to increment from 33 to 66, a few percent at a time, inside of foo).

Upvotes: 2

Rob P.
Rob P.

Reputation: 15071

If I'm understanding your question; the answer is 'No, there is no way for the backgroundworker to automatically report it's progress'.

You'll have to explicitly make calls to .ReportProgress()

bw.DoWork += (a,b) => {
  foo();
  worker.ReportProgress(33);
  baa();
  worker.ReportProgress(66);
  if(..) else {  }
};

You could get clever and do something like build a queue of Actions, call each action and call ReportProgress after each, if you are really dealing with a large number of method calls in your DoWork body.

Upvotes: 2

Related Questions