Reputation: 584
Is there a way to await the calling task?
Async Function DoStuff() As Task
StartDoingOtherStuff()
' Doing stuff
End Function
Async Function StartDoingOtherStuff() As Task
' Doing stuff
Await callingTask
' Finish up
End Function
Note: I want to paralize the task, because it involves uploading a file to multiple destinations. But I want to await the calling task, to delete the file after all uploads are complete.
Upvotes: 0
Views: 454
Reputation: 18310
Based on usr's answer to Get the current Task instance in an async method body, you can do this:
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
By using a lambda expression you can capture the current task and then pass it to itself. Await Task.Delay(1)
is required in order for the async method to return its task so that it can be set to the variable. However, you can remove it if you already have another await before DoOtherStuff()
is called.
Upvotes: 1