Search code examples
c#backgroundworker

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.


Solution

  • 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.