进度条在 winform 中冻结

Progressbar freezes in winform

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

程序的问题是我 progressbar 控件以及 processForm 中的 label 根本不显示。我已经用谷歌搜索了几个小时,但我仍然无法解决它。

这是我的代码 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;
}

您正在 UI 线程中执行您的耗时任务,因此冻结 UI 是正常的。我觉得你应该把你的耗时任务放在BackgroundWorkerDoWork,需要的时候调用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;
    }));
}

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