I would like to know what is the best way or are there any documents/articles that can help me to identify what is the differences of using Parallel.foreach and Task within a normal for each loop, like the following:
case 1 - Parallel.foreach:
Parallel.foreach
{
// Do SOmething thread safe: parsing an xml and then save
// into a DB Server thry respoitory approach
}
case 2 - Task within foreach:
foreach
{
Task t1 = Task.factory.startNew(()=>
{
//Do the same thing as case 1 that is thread safe
}
}
Task.waitall()
While there are almost a 1:4 on the case 1 and case 2 ? So is it means we should always use parallel.foreach or parallel.for if we want to run in parallel within the loop?
What Parallel.ForEach()
does is that it creates a small number of Task
s to process iterations of your loop. Task
s are relatively cheap, but they aren't free, so this tends to improve performance. And the body of your loop executes quickly, the improvement can be really big. This is the most likely explanation for the behavior you're observing.