0

I've a problem with parallel.foreach and async combination. Here is my code -

new Thread(() =>{
     //doing some stuff here
     Parallel.ForEach(.....,ParallelOption,async(j,loopState) =>
     {
        //await some stuff here like:
       // HttpResponseMessage res = await httpClient.GetAsync(url);
      // UpdateUI
     }
}).Start();

Now, my problem is how can I be sure of the loop has completed all jobs? It just ends in few seconds but UIUpdateing will continue for much more time. How its possible to wait for the await httpClient.GetAsync(url) to complete and then update the UI?

Aditi Parikh
  • 1,522
  • 3
  • 13
  • 34
Mahdi
  • 31
  • 1
  • 5
  • are you saying that they are not synchronized? – AsthaUndefined Sep 14 '17 at 05:43
  • @AsthaSrivastava, he's saying that `Parallel.ForEach` completes before all of the tasks started by the loop body have the chance to complete. This is a well-known problem. `Parallel.ForEach` is not designed to work with `async` delegates. – Kirill Shlenskiy Sep 14 '17 at 05:45
  • @KirillShlenskiy exactly , do you have any idea what should i have to do ? anotherway or something esle ? thanks. – Mahdi Sep 14 '17 at 05:50
  • 1
    @Mahdi, use [`Task.WhenAll`](https://stackoverflow.com/a/23139769/1644813) if you're ok with all of the tasks running at the same time, or use TPL Dataflow if you need limited degree of parallelism. – Kirill Shlenskiy Sep 14 '17 at 05:52
  • 1
    You are using a new thread, `Parallel.ForEach` and TPL (async/await). Each tool has a different purpose and should never be combined. Because the actual work is being done using TPL you should just get rid of the thread and `Parallel.ForEach`. If you create many tasks you can wait for them all to complete using `Task.WhenAll`. – Martin Liversage Sep 14 '17 at 07:09

1 Answers1

2

Using async/await for multiple tasks

return Task.WhenAll(ids.Select(i => DoSomething(1, i, blogClient)));

I don't know what's in your actual loop code. If you put more up I can make this more specific. Basically though you use WhenAll to await all of the ascnc tasksf

Brian White
  • 1,265
  • 1
  • 10
  • 16