Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Basic .NET: how to create a task from a method with parameters

I have a sub method with a parameter:

Public Sub mysub(ByVal x As Object)
    [...]
End Sub

To launch it as a thread, I do simply:

Dim x1 as String = "hello"
mythread = New Thread(AddressOf mysub)
mythread.Start(x1)

I would transform mysub in an async function. The online tutorials (this one for example) are only for methods without parameters.

I tried with:

Dim mytask As Task
Dim x1 as String = "hello"
mytask = New Task(Me.mysub, x1)
mytast.Start()

but I get the error:

Error BC30455 Argument not specified for parameter 'x' of 'Public Sub mysub(x As Object)'

like image 923
Marco Sulla Avatar asked Feb 07 '23 17:02

Marco Sulla


1 Answers

Using a sub method will cause code to continue running in paralell, both main and sub code. Notice this might lead to race-conditions (see here), and also you won't be able to 'fully' take advantage of the async / await convenient programming. This is exactly the same scenario as the multi-thread app you suggested at the beginning.

In VB you need to make a lambda custom sub for calling your code, then you can pass any parameter:

    Dim t As Task
    t = New Task(Sub() mysub(param))

    Public Sub mysub(ByVal param As ParamObject)
        [...]
    End Sub

However, for completeness of the answer, let's consider additionally using a function as well. All functions return some information and by using the await keyword it will force the code execution to pause until the result is ready.

Here in VB you need to define a lambda custom function including return type. Then you can call your function including any needed parameters.

    Dim t As Task(Of RetObject)
    t = Task.Run(Function() As RetObject
                     Return myfunction(param)
                 End Function)
    Return Await t

    Public Function myfunction(ByVal param As ParamObject) As RetObject
        [...]
    End Function

What you are doing here is an async wrapper function for sync code. This is discouraged for many reasons (see here). It's always recommended to write code from scratch which takes async-await behavior from the basement.

like image 85
JCM Avatar answered May 23 '23 05:05

JCM