vb.netmultithreadingargumentsbackgroundworkerargument-passing

VB.NET: Sending Multiple Arguments To a Background Worker


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

Solution

  • 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