使用 BackgroundWorker

使用後臺工作程式執行任務。

雙擊工具箱中的 BackgroundWorker 控制元件

http://i.stack.imgur.com/QuRSr.jpg

這是 BackgroundWorker 新增後的顯示方式。

http://i.stack.imgur.com/KmxOU.jpg

雙擊新增的控制元件以獲取 BackgroundWorker1_DoWork 事件,並新增在呼叫 BackgroundWorker 時要執行的程式碼。像這樣的東西:

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

    'Do the time consuming background task here

End Sub

呼叫 BackgroundWorker 執行任務可以在 Button_ClickTextbox_TextChanged 等任何事件中完成,如下所示:

BackgroundWorker1.RunWorkerAsync()

修改 RunWorkerCompleted 事件以捕獲 BackgroundWorker 的任務完成事件,如下所示:

Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
    MsgBox("Done")
End Sub

當工作人員完成分配給它的任務時,這將顯示一個訊息框,說明 Done