如何从返回集合的方法获取数据时调用Background progressChanged

时间:2015-04-15 16:39:45

标签: c# multithreading backgroundworker

我有检索数据的方法。我在后台工作者DoWork中调用该方法。我想在UI上显示进度。如何以百分比显示进度(从0到100执行方法所需的时间)。所以我可以使用bgWorker_ProgressChanged

报告进度
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    MyCollection = GetReportData();            
}

1 个答案:

答案 0 :(得分:1)

首先,您必须指定您希望能够报告进度:

bgWorker.WorkerReportsProgress = true;

然后,修改您的DoWork事件以实际报告进度。您目前正在获取所有数据,这不足以显示 您获取数据的进度。

您需要将GetReportData()细分为可管理的部分。

private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    var bg = (BackgroundWorker)sender;

    var myCollection = new List<SomeClass>();

    while(/* somehow test whether there's more data to get */)
    {
        myCollection.AddRange(GetSomeMoreReportData());

        bg.ReportProgress(0);  // or pass a valid "percentage" if you can calculate it
    }

    // Don't access the UI from a background thread.
    // The safest thing you can do is pass the final data to the RunWorkerCompleted event
    e.Result = myCollection;
}

void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // You're back in the UI thread, update your ProgressBar
}

void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    List<SomeClass> result = (List<SomeClass>)e.Result;

    // You're back in the UI thread, update your UI with the data
}

这一切都非常通用,我对你的环境做了一些假设。尝试一下,根据你的情况对其进行修改......如果你玩了一下并卡住了,那么回帖吧。