您可以尝试使用具有ProgressChanged事件的BackgroundWorker类,该事件允许您在长时间操作期间为用户界面提供中间更新。在DoWork函数中,您可以多次调用ReportProgress并将任何对象传递给ProgressChanged事件以更新 UI。
这是一个简单的例子来展示这个概念。首先BackgroundWorker
从ToolBox
. 该实例将显示在设计器窗口的底部。选择BackgroundWorker
并将WorkerReportsProgress
属性设置为True
。
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim list1 As New List(Of String)
list1.Add("A")
list1.Add("B")
list1.Add("C")
BackgroundWorker1.ReportProgress("50", list1)
Dim list2 As New List(Of String)
list2.Add("1")
list2.Add("2")
list2.Add("3")
BackgroundWorker1.ReportProgress("100", list2)
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As System.Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Dim myList As List(Of String)
myList = e.UserState
For Each str As String In myList
DataGridView1.Rows.Add(str)
Next
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MessageBox.Show("Operation Complete")
End Sub
这是对正在发生的事情的解释。在DoWork
例程中,您将separate thread
在 UI 上执行长时间操作。调用ReportProgress
函数时,可以传递两个参数:一个百分比和一个对象……在这种情况下,第二个参数更重要。在ProgressChanged
例程中,您将从同一个对象中取出e.UserState
并做您想做的事情。这发生在 上,UI thread
因此您可以从此处更新控件。该RunWorkerCompleted
例程在操作完成时被调用,并且也在UI thread
. 重要的是,每当您调用函数时,都会在 theBackgroundWorker
和 the之间执行线程安全的切换。UI
ReportProgress