If I have an async method body like so -
public async Task GetSomething() {
await SendText("hi");
await SendImage("bla.bmp");
}
How can I get the Task object before it is returned to the user when the await kicks in
ie..
public async Task GetSomething() {
myTasks.Add(Task.Current);
await SendText("hi");
await SendImage("bla.bmp");
//some processing
}
so that somewhere else I can do
await Task.WhenAll(myTasks);
Console.WriteLine("All tasks complete");
This is so that I can wait for all tasks to complete before shutting down
This is not directly possible as the language does not have a facility to access the "current" task.
There is a workaround though: Wrap your async method in another method. This other method can get hold of the task once the async method returns (which happens approximately at the first await point).
In all cases I recommend letting the caller add the async Task to your list, not the async method itself. This is useful even from an encapsulation point of view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With