后台工作者ReportProgress没有开火

时间:2014-04-16 14:40:27

标签: c# backgroundworker

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

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

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事件中的消息框从未显示,我的进度条永远不会设置为可见。任何想法可能是什么问题?

1 个答案:

答案 0 :(得分:8)

检查此示例:

    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后立即显示进度。