VB.NET: Sending Multiple Arguments To a Background Worker

10,566

You can wrap your arguments in an object and then pass that object to the worker.

To retrieve it, you can just cast e in the DoWork to your custom type.

here's an example:

' 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
Share:
10,566

Related videos on Youtube

slayernoah
Author by

slayernoah

SO has helped me SO much. I want to give back when I can. And I am #SOreadytohelp http://stackoverflow.com/users/1710577/slayernoah #SOreadytohelp

Updated on July 12, 2022

Comments

  • slayernoah
    slayernoah almost 2 years

    I am trying to use a BackgroundWorker to perform tasks on a separate thread.

    I am able to pass a single argument to the BackgroundWorker as below:

    Send argument to 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
    

    Retrieve argument inside 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
    

    There are only 2 overloaded methods for RunWorkerAsync(). One that takes no arguments and one that takes one argument.

    I want to know:

    1. How can I pass multiple values to BW1.RunWorkerAsync()
    2. How can I retrieve these multiple values from inside BW1_DoWork
    • slayernoah
      slayernoah
      @HansPassant I believe the answer that pacane provided is the helper class method. Could you show how to use a lambda expression to achieve this?
  • slayernoah
    slayernoah about 10 years
    Could you give an example please?
  • Pacane
    Pacane about 10 years
    @slayernoah There you go
  • slayernoah
    slayernoah about 10 years
    Realized that Dim args As WorkerArgs = e.Argument is not necessary in the example above. Looks like I can get the passed values using e.Argument.Something and e.Argument.SomethingElse.