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?
Parallel.ForEachcompletes before all of the tasks started by the loop body have the chance to complete. This is a well-known problem.Parallel.ForEachis not designed to work withasyncdelegates.Task.WhenAllif you're ok with all of the tasks running at the same time, or use TPL Dataflow if you need limited degree of parallelism.Parallel.ForEachand 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 andParallel.ForEach. If you create many tasks you can wait for them all to complete usingTask.WhenAll.