I am running a BackgroundWorker thread to do a time consuming task. The time consuming task is in another class. I need to pass the progress being made on this separate class running on BackgroundWorker back to the Main Form1 class. I am not sure how to approach this. Please provide suggestions. Thank you in advance.
**// Main Form1 UI Class**
public void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
//e.Argument always contains whatever was sent to the background worker
// in RunWorkerAsync. We can simply cast it to its original type.
DataSet ds = e.Argument as DataSet;
this.createje.ProcessData(this.ds);
}
private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Minimum = 0;
this.progressBar1.Maximum = CreateJE.max;
this.progressBar1.Value = e.Recno;
}
**//Other Class called CreateJE**
public void ProcessData(DataSet ds)
{
//Do time consuming task...
for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(500);
**//How do I report progress back to the Main UI?**
//worker.ReportProgress(i * 10);
}
}
}
The cleanest, and most extendable, solution is probably to have your
ProcessData()method raise an event, which theBackgroundWorkeris listening for. This wayProcessData()doesn’t depend on having aBackgroundWorkeras a caller. (You would also need to make a way of canceling out ofProcessData()). You can even re-use theProgressChangedEventArgsif you want. For example (not tested but you get the idea?):The quick and dirty way is to just pass the
BackgroundWorkeras a parameter toProcessData(). This is IMHO rather ugly, though, ties you down to using only BackgroundWorkers, and also forces you to define theBackgroundWorkerin one place (the main form class) and the returned values of ReportProgress in another (the CreateJE class).You could also use a timer and report back progress every X ms, querying the CreateJE object for its progress. This seems in-line with the rest of your code. The hangup with this is it would make your CreateJE class not multi-thread-friendly.