有人可以告诉我如何获得正确的百分比进度数字吗?我的价值超过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!";
}
答案 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);