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()
- I did do my own tests and the result show case 1 perform way better than case 2. The ratio is about like this: sequential vs case 1 vs case 2 = 5s : 1s : 4s
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?