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。