使用BackgroundWorker Class
我需要运行一个从数据库中提取数据的进程,并在没有进度条的标签上以完成百分比的形式报告进度。
我在这种方法中看到的大多数示例都使用了ProgressChanged Event
中的循环,这使得该过程重复:
例如: 调用如下所示的代码会导致多次调用DB,从而重复查询。
Private Sub backgroundWorker1_DoWork(ByVal sender As System.Object, _
ByVal e As DoWorkEventArgs) Handles backgroundWorker1.DoWork
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim i As Integer
For i = 1 To 10
If (worker.CancellationPending = True) Then
e.Cancel = True
Exit For
Else
' This method is rightfully called multiple times.
GetDbDataHere()
worker.ReportProgress(i * 10)
End If
Next
End Sub
此处报告更新:
Private Sub backgroundWorker1_ProgressChanged(ByVal sender As System.Object, _
ByVal e As ProgressChangedEventArgs) Handles
backgroundWorker1.ProgressChanged
resultLabel.Text = (e.ProgressPercentage.ToString() + "%")
End Sub
如果没有进度条,如何运行流程并显示已完成的百分比,但多次调用BackgroundWorker正在处理的方法?