I know there are a few other questions that touch on this topic but I'm trying to figure out if I'm on the right track and if I'm missing something.
Basically, I have a loop that calls an async
method that goes and makes an HTTP call and parses a JSON reply. I am trying to find the best way to call that method. Currently I do it this way:
The method signature: async Task<List<Item>> GetItemData(string item);
foreach(var item in itemList)
{
var test = await GetItemData(item);
}
It works fine, but is slow (itemList
might contain 300-500 items and takes about 150000 ms). I thought I might try to add a Parallel.Foreach
and did it this way:
Parallel.ForEach(itemList, (item) =>
{
var test = GetItemData(item).Result;
});
If I added an async
keyword to the lambda, and omitted the .Result
, it caused issues. So, my question is, is there any reason why I might not want to do it the second way? Calling a .Result
seems counter intuitive to try and do something in an async
fashion but the second method works almost twice as fast.
Thanks in advance!