我尝试在名为ProgressBar1
的进度条上显示百分比进度,现在创建了一个名为BackGrounWorker
的{{1}}并且我有以下代码:
BkW1
现在我的Private Sub Form1_Load(sender as Object, e As EventArgs) Handles MyBase.Load
BKW1.RunWorkerAsync()
End Sub
Private Sub BKW1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BKW1.DoWork
ExternalClass.MyFunction() 'This function is located in another class
End Sub
Private Sub BKW1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BKW1.ProgressChanged
Invoke(Sub()
ProgressBar1.Value = e.ProgressPercentage
End Sub)
End Sub
会遍历ExternalClass.MyFunction()
上可用的所有记录。为什么BackGroundWorker不会在ProgressBar1上显示百分比?我应该在我的外部函数中插入一些引用?
答案 0 :(得分:1)
您必须指定BackgroundWorker实际显示进度(因此在Form_Load
中):
BKW1.WorkerReportsProgress= True
然后你必须实际告诉它报告DoWork
方法的进度(这会触发ProgressChanged
事件):
BKW1.ReportProgress(x)
因此,您可能需要ExternalClass
提出ProgressChanged
事件并在此处调用此行。这是一个简化的例子:
Public Class ExternalClass
Public Event ProgressChanged(percentage As Integer)
Public Function MyFunction() As Boolean
For i As Integer = 0 To 100
'do something
'report the progress
RaiseEvent ProgressChanged(i)
Next
Return True
End Function
End Class
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim MyExternalClass As New ExternalClass
AddHandler MyExternalClass.ProgressChanged, Sub(x) ExternalClass_ProgressChanged(x)
MyExternalClass.MyFunction
End Sub
Private Sub ExternalClass_ProgressChanged(percentage As Integer)
BackgroundWorker1.ReportProgress(percentage)
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
ProgressBar1.value = e.ProgressPercentage
End Sub
请注意,您实际上不需要调用BKW1_ProgressChanged
事件中的方法,因为它在UI线程上运行。这就是BackgroundWorker
更方便使用的原因。
答案 1 :(得分:-1)
您是否尝试在每个循环中在Sub BKW1_DoWork中引发事件ReportProgress()?否则,将不会触发事件ProgressChanged。
这里有一些有趣的代码可以帮助您:http://www.vb-helper.com/howto_net_use_backgroundworker.html