Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vb.net - How to Declare new task as SUB with parameters

As you know we have a new syntax in vb.net with possibility to create inline tasks so we could run it asynchronously.

This is the correct code:

        Dim testDeclaring As New Task(Sub()

                                      End Sub)
        testDeclaring.Start()

but now I need to pass a parameter in the subroutine and I can't find correct syntax for that. Is it possible any way?

like image 214
newbeee Avatar asked Apr 20 '13 11:04

newbeee


2 Answers

It's not possible. However, you could just use the parameters from the current scope:

Public Function SomeFunction()

    Dim somevariable as Integer = 5

    Dim testDeclaring As New Task(Sub()
                                   Dim sum as integer = somevariable + 1  ' No problems here, sum will be 6
                              End Sub)
    testDeclaring.Start()

End Function   
like image 56
Kenneth Avatar answered Oct 27 '22 01:10

Kenneth


If you want to pass a parameter you could do this

    Dim someAction As Action(Of Object) = Sub(s As Object)
                                              Debug.WriteLine(DirectCast(s, String))
                                          End Sub

    Dim testDeclaring As New Task(someAction, "tryme")
    testDeclaring.Start()
like image 33
dbasnett Avatar answered Oct 27 '22 01:10

dbasnett