【问题标题】:Background Worker ReportProgress not firing后台工作人员报告进度未触发
【发布时间】:2014-04-16 14:40:26
【问题描述】:

我是第一次设置后台工作人员。它主要在代码运行和我的停止/取消按钮工作时工作。但是,我也在尝试报告进度以更新进度条,但我根本无法启动它。

我从运行此代码的按钮单击开始代码:

backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.RunWorkerAsync();//this invokes the DoWork event 

我的 Do_Work 方法:

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

            int j = 0;// Count cumulative imported files
            int countDupFiles = 0;// Count number of previously imported csv files
            int countImportedFiles = 0;// Count imported files


            foreach (string folderPath in csvDirList)
            {
                string[] csvFileNames = Directory.GetFiles(@folderPath, "*.csv");
                frmImportCsvData.replaceAll(csvFileNames, folderPath + "\\", "");

                for (int i = 0; i < csvFileNames.Length; i++, j++)
                {
                    string csvFilePath = folderPath + "\\" + csvFileNames[i];

                    if ((worker.CancellationPending == true))
                    {
                        e.Cancel = true;
                        break;
                    }
                    else
                    {
                        if (dataLayer.ImportCsvDataBkgrnd(this, csvFilePath, compIdValue, csvFileCount, i))//new method processes subdirectories if tick box selected
                        {
                            countImportedFiles = countImportedFiles + 1;
                        }
                        else
                        {
                            countDupFiles = countDupFiles + 1;
                        }

                        System.Threading.Thread.Sleep(500);

                    }

                    worker.ReportProgress(j);//tried using worker and backgroundWorker1 but neither works
                    backgroundWorker1.ReportProgress(j);

                    //string proj = j.ToString();
                    //MessageBox.Show(proj);//Displays incrementing j as expected when not commented out
                }
            }
            if (countImportedFiles > 0)
                MessageBox.Show(countImportedFiles + " files were imported.");
            if (countDupFiles > 0)
                MessageBox.Show(countDupFiles + " files were not imported. Matches all ready in Database.");
        }

尝试触发以下任一 ProgressChanged 事件:

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    string tbProgress = (e.ProgressPercentage.ToString() + "%");
    MessageBox.Show(tbProgress + "backgroundWorker1");
    importProgressBar(e.ProgressPercentage);
}

private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    string tbProgress = (e.ProgressPercentage.ToString() + "%");
    MessageBox.Show(tbProgress + "worker");
    importProgressBar(e.ProgressPercentage);
}

最后,我想让 ProgressChanged 事件触发这个方法来更新我的进度条:

public void importProgressBar(int i)
{
    progressTableLayoutPanel.Visible = true;//display progress bar

    int percProgress = 100 * (i + 1) / csvFileCount;

    if (percProgress <= 99)// Required to prevent values above 100 that crash the code
        progressBar.Value = percProgress + 1;//hack that makes the progress bar update when progress value decreases
    progressBar.Value = percProgress;
    percProgressLabel.Text = percProgress.ToString();

    progressTableLayoutPanel.Update();//Required to display all progress bar table contents
    //Thread.Sleep(200);

    if (percProgress >= 100)
    {
        Thread.Sleep(200);
        progressTableLayoutPanel.Visible = false;
    }
}

有效的取消按钮代码如下所示:

private void stopImportButton_Click(object sender, EventArgs e)
        {
             backgroundWorker1.CancelAsync();
        }

我的 ProgressChanged 事件中的消息框永远不会出现,我的进度条也永远不会设置为可见。任何想法可能是什么问题?

【问题讨论】:

    标签: c# backgroundworker


    【解决方案1】:

    检查这个例子:

        BackgroundWorker bgw = new BackgroundWorker();       
        public Form1()
        {
            InitializeComponent();
            label1.Text = "";
            label2.Text = "";
        }
    
       private void button1_Click_1(object sender, EventArgs e)
    {
        if (bgw == null)
        {
            bgw = new BackgroundWorker();
            bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
            bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
            bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
        }
        bgw.WorkerReportsProgress = true;
        bgw.WorkerSupportsCancellation = true;
        bgw.RunWorkerAsync();
    }
    
        void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            int total = 57; //some number (this is your variable to change)!!
    
            for (int i = 0; i <= total; i++) //some number (total)
            {
                System.Threading.Thread.Sleep(100);
                int percents = (i * 100) / total;
                bgw.ReportProgress(percents, i);
                //2 arguments:
                //1. procenteges (from 0 t0 100) - i do a calcumation 
                //2. some current value!
            }
        }
    
        void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            label1.Text = String.Format("Progress: {0} %", e.ProgressPercentage);
            label2.Text = String.Format("Total items transfered: {0}", e.UserState);
        }
    
        void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
             //do the code when bgv completes its work
        }
    }
    

    也许这可以帮助您解决问题...

    并尝试在按钮单击事件中调用 background.doWork 后立即显示进度。

    【讨论】:

    • 我使用的是工具箱中的 backgroundworker 组件。但是像在你的例子中那样手动设置它我让它全部工作。谢谢
    • 我发现了一个错误。如果我多次运行我的导入过程,则会创建一个额外的后台工作程序,等等第二次运行,所有代码运行两次,第三次运行 3 次,等等。 if(bgw=null) 语句阻止创建多个 bgw 的。
    • 完成了,求建议!
    • 进度更改正在触发,但我在事件期间对标签所做的任何更改都不会反映在 UI 中。我简单地把“处理”这个词。但这在执行期间不会在 UI 中改变
    • 对于那些在执行期间需要更新 UI 的人。在这里检查 Control.Invoke link
    猜你喜欢
    • 2022-06-11
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多