vb.net - 如何使用参数将新任务声明为SUB

时间:2013-04-20 11:34:53

标签: vb.net parameters task declare

如您所知,我们在vb.net中有一个新语法,可以创建内联任务,以便我们可以异步运行它。

这是正确的代码:

        Dim testDeclaring As New Task(Sub()

                                      End Sub)
        testDeclaring.Start()

但现在我需要在子例程中传递一个参数,我找不到正确的语法。 有可能吗?

3 个答案:

答案 0 :(得分:10)

如果你想传递参数,你可以这样做

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

答案 1 :(得分:8)

这是不可能的。但是,您可以使用当前范围中的参数:

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   

答案 2 :(得分:0)

不知道您是否在寻找:

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

致谢。