使用 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