How can I report back on the progress of work carried out by a BackgroundWorker in an object in a class library?
I'm so far not sure how to use ReportProgress to feed back the information (can't refer to the calling class, due to circular dependency).
This is an example of the main project which initiates the work:
namespace MainProject {
class MainWindowVM : INotifyPropertyChanged {
private BackgroundWorker _counterWorker;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private int _progress;
public int Progress {
get { return _progress; }
set { _progress = value; NotifyPropertyChanged(); }
}
public MainWindowVM() {
var heavyWorker = new ClassLibrary.HeavyWorkerClass();
_counterWorker = new BackgroundWorker();
_counterWorker.DoWork += new DoWorkEventHandler(_counterWorker_DoWork);
_counterWorker.RunWorkerAsync(heavyWorker);
}
private void _counterWorker_DoWork(object sender, DoWorkEventArgs e) {
var heavyWorker = (ClassLibrary.HeavyWorkerClass)e.Argument;
heavyWorker.StartWork();
Progress = 100;
System.Windows.MessageBox.Show("Work completed!");
}
}
}
And here's an example of the uploading method in a class library:
namespace ClassLibrary {
public class HeavyWorkerClass {
public void StartWork() {
for (int i = 0; i <= 100; i++) {
Thread.Sleep(50);
}
}
}
}
The HeavyWorkerClass
must report its progress somehow. Othwerwise you cannot be supposed to know anything about the progress.
It could for example raise an event at regular intervals. The view model can then subscribe to this event and update its Progress
property accordingly. The view binds to the Progress property of the view model.
Note that it is pretty uncommon for a service or class library method to report its progress though. This is because in most cases there is simply no API that can reveal the current progress of an operation in flight. In situations like this you might as well choose to display an intermediate ProgressBar
or similar in the UI until the operation has finished:
<ProgressBar IsIndeterminate="True" />