在vb.net中创建多个后台工作者

时间:2015-11-12 07:28:00

标签: vb.net background

我正在与后台工作者编写程序,我正在动态创建它但是如何在vb.net中的每个后台工作程序中添加doWork代码

For NumWorkers As Integer = 0 To 3
  NumWorkers = NumWorkers + 1
  ReDim Workers(NumWorkers)
  Workers(NumWorkers) = New BackgroundWorker
  Workers(NumWorkers).WorkerReportsProgress = True
  Workers(NumWorkers).WorkerSupportsCancellation = True
  AddHandler Workers(NumWorkers).DoWork, AddressOf WorkerDoWork
  Workers(NumWorkers).RunWorkerAsync()
Next
 Private Sub WorkerDoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
 ' for first
 End SUb

  Private Sub WorkerDoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
 ' for 2nd
 End SUb

  Private Sub WorkerDoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
 ' for 3rd
 End SUb

  Private Sub WorkerDoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
 ' for 4th
 End SUb

我对最后3个workerDork()感到困惑。我怎样才能在其中添加代码?

2 个答案:

答案 0 :(得分:2)

you Need to add handler and with  different address of each Background worker  
so you have to create each worker dynamically add different address for them .

答案 1 :(得分:2)

这里是你要完成的一个例子

Imports System.ComponentModel

Module Module1

  Sub Main()

    StartSomeThread(
      AddressOf Worker1DoWork,
      AddressOf Worker2DoWork,
      AddressOf Worker3DoWork,
      AddressOf Worker4DoWork)

  End Sub

  Private Sub Worker1DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)

  End Sub
  Private Sub Worker2DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)

  End Sub
  Private Sub Worker3DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)

  End Sub
  Private Sub Worker4DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)

  End Sub

  Private workers As New List(Of BackgroundWorker)

  Public Sub StartSomeThread(ParamArray jobs As Action(Of Object, DoWorkEventArgs)())

    For Each job In jobs

      Dim worker = New BackgroundWorker
      worker.WorkerReportsProgress = True
      worker.WorkerSupportsCancellation = True
      AddHandler worker.DoWork, AddressOf job.Invoke

      workers.Add(worker)

      worker.RunWorkerAsync()

    Next

  End Sub

End Module