1

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!

awh112
  • 1,466
  • 4
  • 22
  • 34
  • When you added `async` to the lambda, did you add await as well? – Barry O'Kane May 23 '17 at 15:10
  • @BarryO'Kane That still won't work. `Parallel.Foreach` is not designed for asynchronous work. – Servy May 23 '17 at 15:11
  • Check this answer: https://stackoverflow.com/a/39796934/5311735 – Evk May 23 '17 at 15:11
  • Based on your question the reason why you are probably not getting the "asynchronous-feel" is due to the fact that JSON deserialization/serialization will block your thread. Not to drive you away from doing `Parallel` work, I would start with doing something as plain as putting your `Json.DeserializeObject()` into it's own thread. `await Task.Run(() => Json...);` an example here https://stackoverflow.com/a/25014988/3645638 – Svek May 23 '17 at 15:12
  • To get all the items in parallel dont await the task directly, do: `foreach(var task in itemList.Select(x => GetItemData(x)).ToList()) { var test = await task; }` Let me know if you got any performance improvement. – Magnus May 23 '17 at 15:14
  • @Evk thanks for pointing me in the direction of that question; I hadn't found that when I was looking before. I'll take a look at some of the suggestions there and see what I can come up with. – awh112 May 23 '17 at 15:41

0 Answers0