Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current Task instance in an async method body

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

like image 538
NoPyGod Avatar asked Jan 13 '13 11:01

NoPyGod


1 Answers

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.

like image 136
usr Avatar answered Sep 18 '22 18:09

usr