0

在完成我的后台工作人员的操作之前,进度条重复了两到三遍

这段代码:

Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    'Load Data
    For i As Integer = 0 To ListData.Count
        BackgroundWorker1.ReportProgress((i / ListData.Count) * 100)
    Next
    If BackgroundWorker1.CancellationPending Then
        e.Cancel = True
    End If
End Sub

Private Sub BackgroundWorker1_ProgressChanged(sender As System.Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    Me.ProgressBar1.Value = e.ProgressPercentage
End Sub

Private Sub BackgroundWorker1_RunWorkerCompleted(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted

    'set datasource of DatagridView
    ProgressBar1.Style = ProgressBarStyle.Blocks

End Sub

在我的加载表单中

BackgroundWorker1.WorkerReportsProgress = True
    BackgroundWorker1.WorkerSupportsCancellation = True
    BackgroundWorker1.RunWorkerAsync()
    ProgressBar1.Style = ProgressBarStyle.Marquee

请帮我

4

1 回答 1

3

你有几个错误。首先,如果你打算显示一个递增的进度条,你应该使用:

ProgressBar1.Style = ProgressBarStyle.Continuous

在您的加载表单中。接下来,您BackgroundWorker1.CancellationPending只有在检查完所有ListData. 为时已晚,您必须在循环的每次迭代中检查它。我也真的怀疑您是否希望循环从 0 变为ListData.Count; 您可能想从 1 开始或转到ListData.Count - 1. 从你的问题我看不出来。你的循环应该看起来更像这样:

For i as Integer = 0 To ListData.Count - 1
    If BackgroundWorker1.CancellationPending Then
        e.Cancel = True
        Exit For
    Else
        ' You should be doing some work here, not just calling ReportProgress
        BackgroundWorker1.ReportProgress(100 * (i+1) / ListData.Count)
    End If
Next

另一个错误是计算(i / ListData.Count) * 100iListData.Count是整数,因此它们的除法将始终为零,直到结束时为 1。相反,将分子乘以 100 以获得百分比。

于 2013-08-21T03:16:28.853 回答