是否可以等待调用任务?

时间:2019-02-28 10:38:35

标签: vb.net asynchronous async-await task

有没有办法等待呼叫任务?

Async Function DoStuff() As Task
    StartDoingOtherStuff()

    ' Doing stuff
End Function

Async Function StartDoingOtherStuff() As Task
    ' Doing stuff

    Await callingTask

    ' Finish up
End Function

注意:我想对任务进行解析,因为它涉及将文件上传到多个目标。但是我想等待调用任务,在所有上传完成后删除文件。

1 个答案:

答案 0 :(得分:1)

根据usr对Get the current Task instance in an async method body的回答,您可以执行以下操作:

Private Async Function DoStuff() As Task
    'Capture the resulting task in a variable.
    Dim t As Task = (
        Async Function() As Task
            Console.WriteLine("DoStuff()")

            'First await. Required in order to return the task to 't'.
            Await Task.Delay(1)

            'Disable warnings:
            '    "Because this call is not awaited (...)"
            '    "Variable 't' is used before it has been assigned a value (...)"

#Disable Warning BC42358, BC42104

            'Call other method.
            DoOtherStuff(t)

#Enable Warning BC42358, BC42104

            'Simulate process.
            Await Task.Delay(3000)
        End Function
    ).Invoke()

    'Await if needed.
    Await t
End Function

Private Async Function DoOtherStuff(ByVal ParentTask As Task) As Task
    Console.WriteLine("DoOtherStuff()")

    'Await parent task.
    Await ParentTask

    Console.WriteLine("DoStuff() finished!")
End Function

通过使用lambda表达式,您可以捕获当前任务,然后将其传递给自身。 Await Task.Delay(1)是必需的,以便异步方法返回其任务,以便可以将其设置为变量。但是,如果在调用DoOtherStuff()之前已经有另一个等待时间,则可以将其删除。