c#带背景工作者的进度条

时间:2016-09-14 09:19:05

标签: c# progress-bar backgroundworker

我在UI中有一个进度条,我希望通过执行每个函数来改变它的进度直到最后。我试过背景工作者。我正在尝试使用backgroundworker_dowork函数实现。如何将其与我正在进行的功能同步。现在,工作只是取得初步进展。如何在每次执行函数时增加它。

我的代码是这样的:

private  void  Ok_Button_Click(object sender, EventArgs e)
    {
                    //set max sixe of progress bar
        elementForm.progressBar1.Maximum = 100;
        //// To report progress from the background worker we need to set this property
        elementForm.backgroundWorker1.WorkerReportsProgress = true;
        //// This event will be raised on the worker thread when the worker starts
        elementForm.backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);

        //// This event will be raised when we call ReportProgress
        elementForm.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
       elementForm.backgroundWorker1.RunWorkerAsync();
method1();
progress=10;
method2();
progress=20
method3();
lastmethod();
progress=100;

}

基本上进度应随着方法的执行而增加。每个方法都在做一些应该增加进度的事情,并且在最后一个名为progress的方法之后应该是100%。

backgroundWorker1_DoWork的代码(我应该怎样做才能将进度增量与方法完成同步)

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {

        if (elementForm.progressBar1.Value < elementForm.progressBar1.Maximum)
        {
            while(progress!=100)
            {

                elementForm.progressBar1.Increment(progress);

                elementForm.progressBar1.CreateGraphics().DrawString(progress.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(elementForm.progressBar1.Width / 2 - 10, elementForm.progressBar1.Height / 2 - 7));


            }
        }
    }

backgroundWorker1_ProgressChanged的代码:

        private void backgroundWorker1_ProgressChanged(object sender,
           ProgressChangedEventArgs e)
    {
        if (elementForm.InvokeRequired)
        {
            elementForm.Invoke(new Action<object, ProgressChangedEventArgs>(backgroundWorker1_ProgressChanged), sender, e);

            return;
        }

        // The progress percentage is a property of e
        elementForm.progressBar1.Value = e.ProgressPercentage;

    }

1 个答案:

答案 0 :(得分:-1)

感谢所有评论。

我将我的功能放在Do_work中,我的进度条监视并与Do_work中的函数调用同步运行。