我正在尝试使用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
答案 0 :(得分:11)
您可以将参数包装在对象中,然后将该对象传递给worker。
要检索它,您只需将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