VB.NET:向后台工作者发送多个参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22531046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.NET: Sending Multiple Arguments To a Background Worker
提问by slayernoah
I am trying to use a BackgroundWorker to perform tasks on a separate thread.
我正在尝试使用 BackgroundWorker 在单独的线程上执行任务。
I am able to pass a single argument to the BackgroundWorker as below:
我可以将单个参数传递给 BackgroundWorker,如下所示:
Send argument to 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
Retrieve argument inside BackgroundWorker:
在 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.
只有 2 个重载方法RunWorkerAsync()。一种不带参数,一种带一种参数。
I want to know:
我想知道:
- How can I pass multiple values to
BW1.RunWorkerAsync() - How can I retrieve these multiple values from inside
BW1_DoWork
- 如何将多个值传递给
BW1.RunWorkerAsync() - 如何从内部检索这些多个值
BW1_DoWork
回答by Pacane
You can wrap your arguments in an object and then pass that object to the worker.
您可以将参数包装在一个对象中,然后将该对象传递给工作人员。
To retrieve it, you can just cast ein the DoWork to your custom type.
要检索它,您只需将eDoWork 转换为您的自定义类型即可。
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

