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?

5
  • are you saying that they are not synchronized? Commented Sep 14, 2017 at 5: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. Commented Sep 14, 2017 at 5:45
  • @KirillShlenskiy exactly , do you have any idea what should i have to do ? anotherway or something esle ? thanks. Commented Sep 14, 2017 at 5:50
  • 1
    @Mahdi, use Task.WhenAll 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. Commented Sep 14, 2017 at 5: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. Commented Sep 14, 2017 at 7:09

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.