进度条在winform中冻结

时间:2015-10-05 20:22:25

标签: c# multithreading winforms progress-bar

我正在尝试处理包含10,000多行的文件并将其存储在数据库中。处理文件通常需要2-3分钟,所以我想显示progressbar

该计划的问题在于progressbar控件以及label中的processForm根本无法显示。我用谷歌搜索了几个小时,但我仍然无法解决它。

enter image description here

这是我的代码 处理文件的btnApplyEOD_Click方法

private void btnApplyEOD_Click(object sender, EventArgs e)
{
    string url = txtEODReport.Text;
    if (url != null)
    {
        using (var file = new System.IO.StreamReader(url))
        {
            int i = 0;
            linesInEOD = File.ReadAllLines(url).Count();

            if (backgroundWorkerEOD.IsBusy != true)
            {
                progressForm = new ProgressForm();
                progressForm.Show();
                backgroundWorkerEOD.RunWorkerAsync();
            }

            while ((line = file.ReadLine()) != null)
            {
                string[] splitLines = line.Split('~');
                switch (splitLines[0])
                {
                    case "01":
                    {
                        BOID = splitLines[1].Trim() + splitLines[2].Trim();
                        break;
                    }
                    .........
                }
                i++;
                currentLine = i;
            }
        }
        ...........
        bindToGridView();
    }

}

我已使用BackgroundWorkerBackgroundWorker_DoWork方法的代码如下:

private void backgroundWorkerEOD_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker workerEOD = sender as BackgroundWorker;
    //for (int i = 1; i <= 10; i++)             //usually works but useless for this scenario
    //{
    //    workerEOD.ReportProgress(i * 10);
    //    System.Threading.Thread.Sleep(500);
    //}

    for (int i = 1; i <= linesInEOD; i++)       // doesn't work at all but it will give accurate progressbar increase 
    {
        workerEOD.ReportProgress(100 * currentLine / linesInEOD);
    }
}

BackgroundWorker_ProgressChanged方法:

private void backgroundWorkerEOD_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressForm.Message = "In progress, please wait... " + e.ProgressPercentage.ToString() + "%";
    progressForm.ProgressValue = e.ProgressPercentage;
}

1 个答案:

答案 0 :(得分:4)

您正在UI线程中执行耗时的任务,因此冻结UI是正常的。我认为您应该在DoWork BackgroundWorker backgroundWorker1.RunWorkerAsync();中执行耗时的任务,并在需要时致电private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { this.PerformTimeConsumingTask(); } public void PerformTimeConsumingTask() { //Time-Consuming Task //When you need to update UI progressForm.Invoke(new Action(() => { progressForm.ProgressValue = someValue; })); }

library(tidyr) # for extract_numeric
library(rvest)
movie <- read_html("http://www.imdb.com/title/tt1490017/")
movie %>%
html_nodes("#titleDetails :nth-child(11)") %>%     
  html_text() %>%      
  extract_numeric()

[1] 6e+07

如果您使用的是.Net 4.5,您还可以考虑使用async/await模式。