进度条百分比

时间:2015-01-30 09:31:58

标签: c# progress

有人可以告诉我如何获得正确的百分比进度数字吗?我的价值超过100% - 似乎无法理解它。

由于

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
        string[] strArray = txtSource.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
        Int32 i = 0;

        foreach (string item in strArray)
        {
            //Thread.Sleep(250);

            string returnMessage = DoAction(item).Replace(nl,"");
            i++;

            backgroundWorker.ReportProgress(i, item + " ..." + returnMessage);                
        }
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
        lblProgress.Text = "Progress: " + e.ProgressPercentage.ToString() + "% complete, processing: " + e.UserState.ToString();
        txtResults.Text += "Processing " + e.UserState.ToString() + nl;
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        btnRun.Enabled = true;
        lblProgress.Text = "Action completed!";            
    }

3 个答案:

答案 0 :(得分:3)

由于您在i的每次迭代中增加strArray,因此在此处使用i作为执行百分比是不正确的,因为它只是执行的确切百分比如果你的数组包含100个项目:

backgroundWorker.ReportProgress(i, item + " ..." + returnMessage);

您只需使用(100 * i) / strArray.Length代替。

答案 1 :(得分:0)

因为您strArray中有超过100件商品。 这样做 -

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker backgroundWorker = (BackgroundWorker)sender;
    string[] strArray = txtSource.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
    Int32 i = 0;
    int iLength = strArray.Length;
    foreach (string item in strArray)
    {
        //Thread.Sleep(250);

        string returnMessage = DoAction(item).Replace(nl,"");
        i++;

        backgroundWorker.ReportProgress(i/iLength , item + " ..." + returnMessage);                
    }
}

答案 2 :(得分:0)

您可能希望将backgroundWorker.ReportProgress(i, item + " ..." + returnMessage);更改为backgroundWorker.ReportProgress(i / strArray.Length , item + " ..." + returnMessage);