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

3

5

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?

Kevel answered 20/4, 2013 at 11:34 Comment(0)
C
10

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   
Carnegie answered 20/4, 2013 at 11:40 Comment(1)
Thank you! That is what I was looking for. BTW, it cause some strange behavior in my context but I guess it's the problem for the other topic.Kevel
P
10

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()
Picrite answered 20/4, 2013 at 14:42 Comment(1)
What about if there's more than one parameter? There's a proper way rather than pass an ArrayList of parameters?Tremulant
M
1

Dont know if you looking for this:

Dim t As Task = New Task(Sub() RemoveBreakPages(doc))

Sub RemoveBreakPages(ByRef doc As Document)
        Dim paragraphs As NodeCollection = doc.GetChildNodes(NodeType.Paragraph, True)
        Dim runs As NodeCollection = doc.GetChildNodes(NodeType.Run, True)
        For Each p In paragraphs
            If CType(p, Paragraph).ParagraphFormat().PageBreakBefore() Then
                CType(p, Paragraph).ParagraphFormat().PageBreakBefore = False
            End If
        Next
    End Sub

Regards.

Magnoliamagnoliaceous answered 12/7, 2018 at 0:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.