I have few async REST services which are not dependent on each other. That is while "awaiting" a response from Service1, I can call Service2, Service3 and so on.
For example, refer below code:
var service1Response = await HttpService1Async();
var service2Response = await HttpService2Async();
// Use service1Response and service2Response
Now, service2Response
is not dependent on service1Response
and they can be fetched independently. Hence, there is no need for me to await response of first service to call the second service.
I do not think I can use Parallel.ForEach
here since it is not CPU bound operation.
In order to call these two operations in parallel, can I call use Task.WhenAll
? One issue I see using Task.WhenAll
is that it does not return results. To fetch the result can I call task.Result
after calling Task.WhenAll
, since all tasks are already completed and all I need to fetch us response?
Sample Code:
var task1 = HttpService1Async();
var task2 = HttpService2Async();
await Task.WhenAll(task1, task2)
var result1 = task1.Result;
var result2 = task2.Result;
// Use result1 and result2
Is this code better than the first one in terms of performance? Any other approach I can use?
I do not think I can use Parallel.ForEach here since it is not CPU bound operation
-- I don't see the logic there. Concurrency is concurrency.Parallel.ForEach
would spawn new threads whereasasync await
would do everything on a single thread.await
) before it is ready.WhenAll
before I doResult
with the idea that it completes all the tasks before .Result is called. Since, Task.Result blocks the calling thread, I presume that if I call it after the tasks are actually completed it would return thre result immediately. I want to validate the understanding.