VB.NET:向后台工作者发送多个参数

时间:2014-03-20 11:08:09

标签: vb.net multithreading arguments backgroundworker argument-passing

我正在尝试使用BackgroundWorker在单独的线程上执行任务。

我能够将一个参数传递给BackgroundWorker,如下所示:

向BackgroundWorker发送参数:

Private Sub btnPerformTasks_Click(sender As System.Object, e As System.EventArgs) Handles btnPerformTasks.Click

    Dim strMyArgument as String = "Test"
    BW1.RunWorkerAsync(strMyArgument)

End Sub

在BackgroundWorker中检索参数:

Private Sub BW1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BW1.DoWork
    Dim strMyValue As String
    strMyValue = e.Argument  'Test
End Sub

RunWorkerAsync()只有2种重载方法。一个不带参数,一个带一个参数。

我想知道:

  1. 如何将多个值传递给BW1.RunWorkerAsync()
  2. 如何从BW1_DoWork
  3. 中检索这些多个值

1 个答案:

答案 0 :(得分:11)

您可以将参数包装在对象中,然后将该对象传递给worker。

要检索它,您只需将DoWork中的e转换为自定义类型。

这是一个例子:

' Define a class named WorkerArgs with all the values you want to pass to the worker.
Public Class WorkerArgs
    Public Something As String
    Public SomethingElse As String
End Class

Dim myWrapper As WorkerArgs = New WorkerArgs()
' Fill myWrapper with the values you want to pass

BW1.RunWorkerAsync(myWrapper)

' Retrieve the values
Private Sub bgw1_DoWork(sender As Object, e As DoWorkEventArgs)
        ' Access variables through e
        Dim args As WorkerArgs = e.Argument
        ' Do something with args
End Sub