Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .Net Parallel Extensions (Parallel.Invoke) for multiple asynchronous calls?

Currently I have a section of code that needs to make about 7 web service calls to various providers for data. Each call takes a several seconds to execute, so I would like to run them in parallel to speed things up.

I have wrapped my 7 calls in a Parallel.Invoke which works great at running a couple things at the same time, but on a 2 core server, it will only execute 2 at a time, one per core. Since all I am doing is waiting around for the web service calls to return I would want it to go fetch all 7 and wait for them to come back.

Is there no way to do this? Or perhaps my approach is wrong? Maybe I need to create asynchronous calls to the web services? But then how to wait for them all to come back before moving on?

like image 355
puffpio Avatar asked Sep 14 '10 22:09

puffpio


1 Answers

but on a 2 core server, it will only execute 2 at a time, one per core

I would question this - Parallel.Invoke will typically run many more tasks than cores in your system.

That being said, if you're using asynchronous method call invocations, I would recommend using Task.Factory.FromAsync(...) to generate your seven distinct tasks.

This provides the flexibility of doing other work while the tasks execute, then calling Task.WaitAll (or Task.WaitAny) when you decide to use the results.

Parallel.Invoke, on the other hand, will always block until all seven complete.

like image 89
Reed Copsey Avatar answered Oct 06 '22 01:10

Reed Copsey