vb.net VB中如何在线程中传递多个参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4018282/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:06:20  来源:igfitidea点击:

How to pass multiple parameters in thread in VB

vb.netmultithreadingvisual-studio

提问by elcool

I'm looking to pass two or more parameters to a thread in VB 2008.

我希望将两个或多个参数传递给 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

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

回答by Dario

First of all: AddressOfjust gets the delegate to a function - you cannot specify anything else (i.e. capture any variables).

首先AddressOf只是获取一个函数的委托-您不能指定任何其他内容(即捕获任何变量)。

Now, you can start up a thread in two possible ways.

现在,您可以通过两种可能的方式启动线程。

  • Pass an Actionin the constructor and just Start()the thread.
  • Pass a ParameterizedThreadStartand forward oneextra object argument to the method pointed to when calling .Start(parameter)
  • Action在构造函数中传递 an并且只传递Start()线程。
  • 传递 aParameterizedThreadStart并将一个额外的对象参数转发给调用时指向的方法.Start(parameter)

I consider the latter option an anachronism from pre-generic, pre-lambda times - which have ended at the latest with VB10.

我认为后一个选项是前泛型、前 lambda 时代的不合时宜 - 最迟以 VB10 结束。

You coulduse that crude method and create a list or structure which you pass to your threading code as this single object parameter, but since we nowhave closures, you can just create the thread on an anonymous Subthat knows all necessary variables by itself (which is work performed for you by the compiler).

可以使用这种粗略的方法并创建一个列表或结构,将其作为单个对象参数传递给您的线程代码,但是由于我们现在有闭包,您可以只在匿名上创建线程,它Sub自己知道所有必要的变量(它是编译器为您执行的工作)。

Soo ...

苏...

Dim Evaluator = New Thread(Sub() Me.TestThread(goodList, 1))

It's really just that ;)

真的就是这样;)

回答by jgauffin

Something like this (I'm not a VB programmer)

像这样的东西(我不是 VB 程序员)

Public Class MyParameters
    public Name As String
    public Number As Integer
End Class



newThread as thread = new Thread( AddressOf DoWork)
Dim parameters As New MyParameters
parameters.Name = "Arne"
newThread.Start(parameters);

public shared sub DoWork(byval data as object)
{
    dim parameters = CType(data, Parameters)

}

回答by Manuel Alves

Dim evaluator As New Thread(Sub() Me.testthread(goodList, 1))
With evaluator
.IsBackground = True ' not necessary...
.Start()
End With

回答by Konrad Rudolph

Well, the straightforward method is to create an appropriate class/structure which holds all your parameter values and pass that to the thread.

好吧,直接的方法是创建一个适当的类/结构来保存所有参数值并将其传递给线程。

Another solution in VB10 is to use the fact that lambdas create a closure, which basically means the compiler doing the above automatically for you:

VB10 中的另一个解决方案是利用 lambdas 创建一个closure的事实,这基本上意味着编译器会自动为您执行上述操作:

Dim evaluator As New Thread(Sub()
                                testthread(goodList, 1)
                            End Sub)

回答by Jay

In addition to what Dario stated about the Delegates you could execute a delegate with several parameters:

除了 Dario 所说的关于委托的内容之外,您还可以使用多个参数执行委托:

Predefine your delegate:

预定义您的委托:

Private Delegate Sub TestThreadDelegate(ByRef goodList As List(Of String), ByVal coolvalue As Integer)

Get a handle to the delegate, create parameters in an array, DynamicInvoke on the Delegate:

获取委托的句柄,在数组中创建参数,在委托上使用 DynamicInvoke:

Dim tester As TestThreadDelegate = AddressOf Me.testthread
Dim params(1) As Object
params(0) = New List(Of String)
params(1) = 0

tester.DynamicInvoke(params)

回答by Hans Olsson

Just create a class or structure that has two members, one List(Of OneItem)and the other Integerand send in an instance of that class.

只需创建一个具有两个成员(一个List(Of OneItem)和另一个)的类或结构,Integer然后发送该类的一个实例。

Edit: Sorry, missed that you had problems with one parameter as well. Just look at Thread Constructor (ParameterizedThreadStart)and that page includes a simple sample.

编辑:对不起,错过了你也有一个参数的问题。只需查看线程构造函数 (ParameterizedThreadStart),该页面就包含一个简单示例。

回答by OverrockSTAR

I think this will help you... Creating Threads and Passing Data at Start Time!

我认为这会对您有所帮助... 在开始时创建线程和传递数据

Imports System.Threading

' The ThreadWithState class contains the information needed for 
' a task, and the method that executes the task. 
Public Class ThreadWithState
    ' State information used in the task. 
    Private boilerplate As String 
    Private value As Integer 

    ' The constructor obtains the state information. 
    Public Sub New(text As String, number As Integer)
        boilerplate = text
        value = number
    End Sub 

    ' The thread procedure performs the task, such as formatting 
    ' and printing a document. 
    Public Sub ThreadProc()
        Console.WriteLine(boilerplate, value)
    End Sub  
End Class 

' Entry point for the example. 
' 
Public Class Example
    Public Shared Sub Main()
        ' Supply the state information required by the task. 
        Dim tws As New ThreadWithState( _
            "This report displays the number {0}.", 42)

        ' Create a thread to execute the task, and then 
        ' start the thread. 
        Dim t As New Thread(New ThreadStart(AddressOf tws.ThreadProc))
        t.Start()
        Console.WriteLine("Main thread does some work, then waits.")
        t.Join()
        Console.WriteLine( _
            "Independent task has completed main thread ends.")
    End Sub 
End Class 
' The example displays the following output: 
'       Main thread does some work, then waits. 
'       This report displays the number 42. 
'       Independent task has completed; main thread ends.

回答by ISCI

Pass multiple parameter for VB.NET 3.5

为 VB.NET 3.5 传递多个参数

 Public Class MyWork

    Public Structure thread_Data            
        Dim TCPIPAddr As String
        Dim TCPIPPort As Integer            
    End Structure

    Dim STthread_Data As thread_Data
    STthread_Data.TCPIPAddr = "192.168.2.2"
    STthread_Data.TCPIPPort = 80  

    Dim multiThread As Thread = New Thread(AddressOf testthread)
    multiThread.SetApartmentState(ApartmentState.MTA)
    multiThread.Start(STthread_Data)     

    Private Function testthread(ByVal STthread_Data As thread_Data) 
        Dim IPaddr as string = STthread_Data.TCPIPAddr
        Dim IPport as integer = STthread_Data.TCPIPPort
        'Your work'        
    End Function

End Class