0

当以下代码执行时,进度条不会走到最后,当它完成 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");
    }
}
4

2 回答 2

1

改变backgroundWorker1.ReportProgress(i);

至:

backgroundWorker1.ReportProgress(i+1);

将循环更改为:

for (int i = 1; i <= 100; i++)
于 2013-10-24T07:51:57.957 回答
1

我已经重现了你的问题。问题出在DoWork方法太快,进度条重绘跟不上。如果您尝试将 Thread.Sleep 更改为更大的间隔(我尝试了 300 毫秒),您可能会看到完整的画作。

但是,如果在将 Progressbar.Value 设置为零之前将 MessageBox.Show("Done") 移动,则可以帮助重新绘制进度条

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        MessageBox.Show("Cancelled");
        progressBar1.Value = 0;
    }
    else
    {
        MessageBox.Show("Done");
        progressBar1.Value = 0;                
    }
}
于 2013-10-24T08:06:48.247 回答