Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# async/await - multiple tasks with one preferred

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;
like image 969
Paul Gelardi Avatar asked Oct 10 '17 18:10

Paul Gelardi


1 Answers

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;
like image 52
Servy Avatar answered Oct 16 '22 16:10

Servy