我正在尝试使用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个重载方法。一种不带参数,一种带一个参数。
我想知道:
BW1.RunWorkerAsync()
BW1_DoWork
您可以将参数包装在一个对象中,然后将该对象传递给工作人员。
要检索它,您只需将 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
最简单的方法是使用参数数组。
调用BackgroundWorker:
Dim var1 As String = "Test"
Dim var2 As Integer = 4
BackgroundWorker1.RunWorkerAsync({var1, var2})
通过Array ID设置BackgroundWorker中的变量。
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
如果你要传递太多变量并且你不记得数组ID,你可以使用Dictionary(Of String, Object)而不是简单的数组,然后你可以通过Dictionary Key (Name)获取变量的内容。