C # async / await - multiple tasks with one preferred

I have the following script / requirement:

I have two tasks: task A and task B, which return the same data type. If task A, after completion, has data in its result, I need to return the result of task A - otherwise I will return the result of result B.

I'm trying to optimize performance for concurrency, and I'm not sure if there is a better way than what I'm doing. It 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; 
+5
source share
1 answer

Just write the code the way your requirements are read. returns the result of A if it is not null, in which case returns the result of B.

 return await taskA ?? await taskB; 
+12
source

Source: https://habr.com/ru/post/1272513/


All Articles