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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With