Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start async operations, then await later

I'm just now starting to play with async and await. I have 8 separate db calls, some dependent on others. I'd like to be able to kick off 3 async methods, then when a certain 1 returns, kick off 3 others, then when a certain 1 returns from that, kick off 2 more. I am currently using 3 Parallel.Invoke methods to accomplish this, but each parallel has to wait until ALL methods return. I only care about 1 method returning, the others can run in the background until an await Task.WhenAll(t1,t2,t3,...,t6) at the end. Is there a way to pull this off with async/await?

I understand that await isn't blocking, but it is stopping execution of my main method (w/the 8 db calls) until the value returns from the method (just like a synchronous method does).

like image 338
DougJones Avatar asked Sep 21 '13 21:09

DougJones


1 Answers

You can use Task.WhenAny to wait for any one of several tasks:

var completedTask = await Task.WhenAny(t1, t2, t3, ...);

If you have a more complex dependency structure, then I recommend representing that with async methods as such:

static async Task DoMasterOperationAsync()
{
  var result = await StartSomething();
  await Task.WhenAll(DoComplexOperationAsync(), result.NextT1Async());
}

static async Task DoComplexOperationAsync()
{
  var result1 = await T1Async();
  await Task.WhenAll(result1.NextT1Async(), result1.NextT2Async(), result1.NextT3Async());
}

await Task.WhenAll(DoMasterOperationAsync(), t2, t3, ...);
like image 77
Stephen Cleary Avatar answered Nov 15 '22 20:11

Stephen Cleary