BackgroundWorker中的ReportProgress

时间:2013-08-21 02:56:10

标签: vb.net

在我的backgroundworker上完成操作之前,进度条会重复两到三次

此代码:

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

请帮帮我

1 个答案:

答案 0 :(得分: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) * 100; iListData.Count是整数,因此它们的除法将始终为零,直到结束时,它将为1.而是将分子乘以100得到百分比。