1

我有两个类,来自 WPF 的主类和在“PersistDataToTable.Persist”内称为“PersistDataToTable”的子类我有一个循环,我想将该循环增量传递回主 WPF 类以显示在进度条中。我有一个后台工作线程运行命中循环的方法,我只是不知道如何从后台工作线程将数据返回给 ReportProgress 方法。

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();
    }
4

2 回答 2

1

您可以将worker.ReportProgressas传递给Action<Int>您的Persist方法,以便它更新回您的 UI

例子:

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);
        }
    }
}
于 2013-08-05T23:47:58.010 回答
0

使用事件 DoWork 和 RunWorkerComplete。这是一个计数到 10 并将结果传递给标签的示例:

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
}

关于此的 msdn 文章:http: //msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.dowork.aspx

于 2013-08-05T21:44:55.803 回答