Background worker 類的基本實現
你需要匯入 System.ComponentModel 才能使用後臺工作程式
Imports System.ComponentModel
然後宣告一個私有變數
Private bgWorker As New BackgroundWorker
你需要為後臺工作程式的 DoWork 和 RunWorkerCompleted 事件建立兩個方法並分配它們。
Private Sub MyWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
'Add your codes here for the worker to execute
End Sub
當工人完成工作時,將執行以下子程式
Private Sub MyWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)
'Add your codes for the worker to execute after finishing the work.
End Sub
然後在你的程式碼中新增以下行以啟動後臺工作程式
bgWorker = New BackgroundWorker AddHandler bgWorker.DoWork, AddressOf MyWorker_DoWork AddHandler bgWorker.RunWorkerCompleted, AddressOf MyWorker_RunWorkerCompleted `bgWorker.RunWorkerAsync()`
當你呼叫 RunWorkerAsync()
函式時,將執行 MyWorker_DoWork。