Reputation: 4492
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:
BW1.RunWorkerAsync()
BW1_DoWork
Upvotes: 4
Views: 11348
Reputation: 83
The easiest way to do it is by using an array of arguments.
Calling the BackgroundWorker:
Dim var1 As String = "Test"
Dim var2 As Integer = 4
BackgroundWorker1.RunWorkerAsync({var1, var2})
Setting the variables in the BackgroundWorker by Array ID.
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim var1 As String = e.Argument(0)
Dim var2 As Integer = e.Argument(1)
End Sub
If you are about to pass too many variables and you can't remember the Array ID you can use Dictionary(Of String, Object) instead of a simple array then you can get the variable's content by the Dictionary Key (Name).
Upvotes: 0
Reputation: 21481
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
Upvotes: 13