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).
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, ...);
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