Webapi2 - Return from controller action after one task completes, but continue with further Async processing

Viewed 5217

I have a question about Webapi2

My application is fully async/await, but I want to optimize the last part. I have a hard time finding out, so is there any way to do the following?

An example of a webapi2 controller:

 private async Task<Foo> Barfoo(Bar foo)
 {
     //some async function
 }     

 public async Task<IHttpActionResult> Foo(Bar bar)
 {
     List<Task> tasks=new List<Task>();
     var actualresult=Barfoo(bar.Bar);
     tasks.Add(actualresult);
     foreach(var foobar in bar.Foo)
     {
         //some stuff which fills tasks
     }
     await Task.WhenAll(tasks);
     return Ok(actualresult.Result);
 }

Just one function is needed for the client, so what I want is more like this:

 private async Task<Foo> Barfoo(Bar foo)
 {
   //some async function  
 }     

 public async Task<IHttpActionResult> Foo(Bar bar)
 {
     List<Task> tasks=new List<Task>();
     var actualresult=Barfoo(bar.Bar);
     return Ok(actualresult.Result);

     foreach(var foobar in bar.Foo)
     {
         //some stuff which fills tasks for extra logic, not important for the client
     }

     await Task.WhenAll(tasks);
 }
3 Answers
Related