如何使用BackgroundWorker报告进度?

时间:2014-09-24 09:35:23

标签: c# wpf progress-bar backgroundworker

伙计们我正在尝试学习wpf,因此我创建了一个应用程序,其任务是更新SQL数据库表中的某些记录。现在因为有数千条记录,所以需要一些时间来更新所有记录,所以我想要做的是,在记录更新过程中显示进度(通过使用进度条或在标签中显示%)。

现在我一直在阅读有关背景工作者以及如何显示进度的内容,但我还不清楚整个概念。现在通过一些教程,我试图实现后台工作和进步,但问题是,我陷入了循环。

我的MainWindow.xaml.cs代码:

public MainWindow()
{
    InitializeComponent();
    bw.WorkerReportsProgress = true;
    bw.WorkerSupportsCancellation = true;
}

private BackgroundWorker bw = new BackgroundWorker();

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;

    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);
            worker.ReportProgress((i * 10));
            StudyMode.Update up = new Update();
            up.UpdateCompanyList();
        }
    }
}

private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    this.label1.Content = (e.ProgressPercentage.ToString() + "%");
}

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if ((e.Cancelled == true))
    {
        this.label1.Content = "Canceled!";
    }

    else if (!(e.Error == null))
    {
        this.label1.Content = ("Error: " + e.Error.Message);
    }

    else
    {
        this.label1.Content = "Done!";
    }
}


private void btnStart_Click(object sender, RoutedEventArgs e)
{
    if (bw.IsBusy != true)
    {
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        bw.RunWorkerAsync();
    }
}

private void btnEnd_Click(object sender, RoutedEventArgs e)
{
    if (bw.WorkerSupportsCancellation == true)
    {
        bw.CancelAsync();
    }
}

在StudyMode类中,我有:

public void UpdateCompanyList()
 {
            try
            {
                for (int i = 1; i <= EndLimit; i++) //loop end limit dynamic
                {
                    string Url = "..some API link....";
                    Parser objParser = new Parser();
                    objParser.UpdateCompanyList(Url);
                }
                MessageBox.Show("Company Names Updated");
                SomeMethod(); //this method takes time as it updates all the company profiles..
                MessageBox.Show("Company Profiles Updated");
            }
            catch (Exception ex)
            {
                // Logging exception here
            }
        }

现在你可以看到,在我的方法中,我有两个MessageBox。现在当我运行上面的代码并按下开始按钮时,UpdateCompanyList执行,因为我得到两个消息框,然后标签更新到10%,然后消息框再次出现,然后标签更新到20%,依此类推。因此该方法重复10次(100%)然后停止执行。我究竟做错了什么 ?如何在执行UpdateCompanyList()方法时更新进度?

0 个答案:

没有答案