I have two classes, the main from WPF and a child class called 'PersistDataToTable' inside 'PersistDataToTable.Persist' I have a loop and I want to pass that loop incrament back to the main WPF class to show in the progress bar. I have a backgroundworker thread running the method that hits the loop, I just don't know how to get the data back to the ReportProgress method from the backgroundworker thread.
private void PersistDataToDb(object sender, RoutedEventArgs e)
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += delegate(object o, DoWorkEventArgs args)
{
PersistDataToTable persistData = new PersistDataToTable();
persistData.Persist(seriesId);
worker.ReportProgress(loop incrament from persist()??);
};
worker.ProgressChanged += delegate(object o, ProgressChangedEventArgs args)
{
int percentage = args.ProgressPercentage;
progressBar.Value = percentage;
};
worker.RunWorkerAsync();
}
You could pass the worker.ReportProgress
as an Action<Int>
into your Persist
method so it updates back to your UI
Example:
private void PersistDataToDb(object sender, RoutedEventArgs e)
{
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += delegate(object o, DoWorkEventArgs args)
{
PersistDataToTable persistData = new PersistDataToTable();
persistData.Persist(seriesId, worker.ReportProgress);
};
worker.ProgressChanged += delegate(object o, ProgressChangedEventArgs args)
{
int percentage = args.ProgressPercentage;
progressBar.Value = percentage;
};
worker.RunWorkerAsync();
}
public class PersistDataToTable
{
public void Persist(int seriesId, Action<int> progresscallback)
{
// set the progress and call the Action(worker.ReportProgress)
for (int i = 0; i < 100; i++)
{
progresscallback.Invoke(i);
}
}
}
Use the events DoWork and RunWorkerComplete. Here is an example counting to 10 and passing the result to a label:
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
label1.Text = e.Result.ToString(); // getting the result set in DoWork
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
int value = 0;
for (int i = 0; i < 10; i++)
value++;
e.Result = value; // setting result for RunWorkerCompleted
}
The msdn article about this: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.dowork.aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.