执行以下代码时,进度条不会结束,当完成90%时,会显示消息框。我发现for循环的问题,但不知道里面的真正问题是什么。请帮忙。我也在stackoverflow中搜索了同样的问题。但没有找到任何解决方案。
这是我的代码:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
break;
}
backgroundWorker1.ReportProgress(i);
Thread.Sleep(100);
}
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("Cancelled");
progressBar1.Value = 0;
}
else
{
progressBar1.Value = 0;
MessageBox.Show("Done");
}
}
答案 0 :(得分:1)
更改backgroundWorker1.ReportProgress(i);
要:
backgroundWorker1.ReportProgress(i+1);
或将循环更改为:
for (int i = 1; i <= 100; i++)
答案 1 :(得分:1)
我已经复制了你的问题。问题在于DoWork方法太快而且条形图的进度条重绘无法跟上。如果您尝试将Thread.Sleep更改为更大的间隔(我已经尝试了300毫秒),您可以看到完整的绘画。
但是,如果您在设置为零之前将MessageBox.Show(“Done”)移动到progressbar.Value
,则可以帮助重绘画中的进度条。private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("Cancelled");
progressBar1.Value = 0;
}
else
{
MessageBox.Show("Done");
progressBar1.Value = 0;
}
}