[vb.net] How to pass multiple parameters in thread in VB

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

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

This question is related to vb.net multithreading visual-studio

The answer is


Pass multiple parameter for 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

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

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:

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

tester.DynamicInvoke(params)

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:

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

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

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.


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.

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

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)

}

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.

  • Pass an Action in the constructor and just Start() the thread.
  • Pass a ParameterizedThreadStart and forward one extra object argument to the method pointed to when calling .Start(parameter)

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

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).

Soo ...

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

It's really just that ;)


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

Examples related to vb.net

How to get parameter value for date/time column from empty MaskedTextBox HTTP 415 unsupported media type error when calling Web API 2 endpoint variable is not declared it may be inaccessible due to its protection level Differences Between vbLf, vbCrLf & vbCr Constants Simple working Example of json.net in VB.net How to open up a form from another form in VB.NET? Delete a row in DataGridView Control in VB.NET How to get cell value from DataGridView in VB.Net? Set default format of datetimepicker as dd-MM-yyyy How to configure SMTP settings in web.config

Examples related to multithreading

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Waiting until the task finishes What is the difference between Task.Run() and Task.Factory.StartNew() Why is setState in reactjs Async instead of Sync? What exactly is std::atomic? Calling async method on button click WAITING at sun.misc.Unsafe.park(Native Method) How to use background thread in swift? What is the use of static synchronized method in java? Locking pattern for proper use of .NET MemoryCache

Examples related to visual-studio

VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio? How to download Visual Studio Community Edition 2015 (not 2017) Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio Code pylint: Unable to import 'protorpc' Open the terminal in visual studio? Is Visual Studio Community a 30 day trial? How can I run NUnit tests in Visual Studio 2017? Visual Studio 2017: Display method references