I have a list of items and for each item i need to execute several async API requests and process the responses, i have seen several implementation and they are all similar when it comes to execution time but i would like to know the difference between them.
Approach 1
Parallel.ForEach(items, new ParallelOptions { MaxDegreeOfParallelism = 10 }, item =>
{
var response = item.propertyOne.GetAsync().GetAwaiter().GetResult();
//process it
var response = item.propertyTwo.GetAsync().GetAwaiter().GetResult();
//process it
var response = item.propertyThree.GetAsync().GetAwaiter().GetResult();
//process it
});
Approach 2
Parallel.ForEach(items, new ParallelOptions { MaxDegreeOfParallelism = 10 }, item =>
{
Task.Run(async () =>
{
var response = await item.propertyOne.GetAsync();
}).GetAwaiter().GetResult();
//process it
Task.Run(async () =>
{
var response = await item.propertyTwo.GetAsync();
}).GetAwaiter().GetResult();
//process it
Task.Run(async () =>
{
var response = await item.propertyThreee.GetAsync();
}).GetAwaiter().GetResult();
//process it
});
Approach 3 assume some bounding mechanism is applied in order not to flood the system with tasks
List<Task> tasksToAwait = new List<Task>();
foreach (var item in items)
{
tasksToAwait.Add(Task.Run(async () =>
{
var response = await item.propertyOne.GetAsync();
//process it
var response = await item.propertyTwo.GetAsync();
//process it
var response = await item.propertyThree.GetAsync();
//process it
}));
}
await Task.WhenAll(taskToAwait);
Notes:
- i am using GetAwaiter().GetResult() instead of Wait() because it doesnt swallow exceptions.
- the requests must be awaited somehow in order to process the response.
- this is executed as background task so i dont mind blocking the calling thread.
- the third approach was slightly faster than the other two and the second was slightly faster than the first.
- i have no control over the async API called through GetAsync().
Which one of these is recommended and if none what do you suggest? Also, how are they different and why is there an execution time difference?