Wednesday, September 29, 2010 1:20 PM
For Each mywebserviceCall In mywebserviceCalls Thread = New Thread(New ParameterizedThreadStart(AddressOf mywebserviceCallFunction)) Thread.IsBackground = True Thread.Name = mywebserviceCall Thread.Start(mywebserviceCall) Threads.Add(Thread) Next
I am bit confused. Is that parallel approach same as multi threading? Let me ask you with scenrio and code.
I have a multi threading app which calls 10+ webservices async. For each webservice call I am creating a thread.
code is simply as shown above. If I replace that with parallel.foreach, as far as I researched, It will be multi tasking rather than multi threading.
what are pons and pros and cons, advantage and disadvantages of 2 approaches? Can we say parallel foreach makes it faster and more cpu efficient?
Wednesday, September 29, 2010 2:09 PM
The tasks are based on the thread pool in .NET 4.0.
Parallel.For function is based on TPL tasks. Tasks are based the ThreadPool. If you are using WebServices calls you do not control the execution time of each call (depend on the web trafic). If you use TPL Task you actually use the ThreadPool for each call, you risk to waste the threads of the ThreadPool.
I have written an article called "Why give up the threads?", where I explained why we should use TPL: http://msmvps.com/blogs/brunoboucard/archive/2010/04/09/parallel-programming-task-oriented-parallel-part-1.aspx
If you use Parallel.ForEach, you will use internaly the threads from the ThreadPool and once your treated finished, theses threads will be availlable for a next treatment. With TPL you will reduce your memory footprint and you gain more controls (cancelling, manage exceptions, information status ...) than traditional threads.
To answer about best practices:
- When your code needs to compute some algorithms, the Tasks are often perfects.
- If you treat a lot of data, the TPL with Parallel.For & Parallel.ForEach API will be good. In PLINQ every thing is dedicated to treat data.
- If your code is waiting for asychronous API, prefer APM style. In your case you are in asychronous mode (Web Service are perfects in APM). I invite you to read the article in the latest MSDN magazine about asynchronous programming: http://msdn.microsoft.com/en-us/magazine/ff959203.aspx
Microsoft has just release a new book call "Parallel Programming with Microsoft .NET". You can read this book at: