如何在VB中的线程中传递多个参数 [英] How to pass multiple parameters in thread in VB
问题描述
我希望将两个或多个参数传递给VB 2008中的线程.
I'm looking to pass two or more parameters to a thread in VB 2008.
以下方法(已修改)无需参数即可正常工作,并且状态栏的更新非常酷. 但是我似乎无法使它使用一个,两个或多个参数.
The following method (modified) works fine without parameters, and my status bar gets updated very cool-y. But I can't seem to make it work with one, two or more parameters.
这是我想在按下按钮时应该发生的事情的伪代码:
This is the pseudo code of what I'm thinking should happen when the button is pressed:
Private Sub Btn_Click()
Dim evaluator As New Thread(AddressOf Me.testthread(goodList, 1))
evaluator.Start()
Exit Sub
这是testthread方法:
This is the testthread method:
Private Sub testthread(ByRef goodList As List(Of OneItem), ByVal coolvalue As Integer)
StatusProgressBar.Maximum = 100000
While (coolvalue < 100000)
coolvalue = coolvalue + 1
StatusProgressBar.Value = coolvalue
lblPercent.Text = coolvalue & "%"
Me.StatusProgressBar.Refresh()
End While
End Sub
推荐答案
首先:AddressOf
只是获取函数的委托-您不能指定其他任何内容(即捕获任何变量)
First of all: AddressOf
just gets the delegate to a function - you cannot specify anything else (i.e. capture any variables).
现在,您可以通过两种可能的方式启动线程.
Now, you can start up a thread in two possible ways.
- 在构造函数中传递
Action
并仅Start()
线程. - 传递
ParameterizedThreadStart
并将一个额外的对象参数传递给调用.Start(parameter)
时指向的方法
- Pass an
Action
in the constructor and justStart()
the thread. - Pass a
ParameterizedThreadStart
and forward one extra object argument to the method pointed to when calling.Start(parameter)
我认为后一种选择是前通用,前lambda时代的不合时宜-最迟在VB10结束了.
I consider the latter option an anachronism from pre-generic, pre-lambda times - which have ended at the latest with VB10.
您可以使用该粗略方法并创建一个列表或结构,并将其作为此单个对象参数传递给线程代码,但是由于我们现在有闭包,您可以仅在匿名Sub
上创建线程,该Sub
本身知道所有必需的变量(编译器为您完成的工作).
You could use that crude method and create a list or structure which you pass to your threading code as this single object parameter, but since we now have closures, you can just create the thread on an anonymous Sub
that knows all necessary variables by itself (which is work performed for you by the compiler).
嘘...
Dim Evaluator = New Thread(Sub() Me.TestThread(goodList, 1))
实际上就是;)
这篇关于如何在VB中的线程中传递多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!