I have the following scenario/requirement:
I have two tasks, task A and task B, which both return the same type of data. If task A, upon completion, has data in its result, I need to return the result of Task A - otherwise I return the result of task B.
I'm trying to performance optimize this for parallellism and I'm unsure if there's a better way than what I'm doing. This seems like a lot of code to do what I want.
var firstSuccessfulTask = await Task.WhenAny(taskA, taskB);
if (firstSuccessfulTask != taskA)
{
await taskA;
}
if (taskA.Result != null)
{
return taskA.Result;
}
return await taskB;
Just write the code just the way your requirements read. return the result of A, unless it's null, in which case, return the result of B.
return await taskA ?? await taskB;
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