Alex Rivera | Logout

Parallel.ForEach vs Task.Factory.StartNew

Asked 2011-02-15T20:33:34.263
281

What is the difference between the below code snippets? Won't both be using threadpool threads?

For instance if I want to call a function for each item in a collection,

Parallel.ForEach<Item>(items, item => DoSomething(item));

vs

foreach(var item in items)
{
  Task.Factory.StartNew(() => DoSomething(item));
}
Edit
Report

1 Answer

17

Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.

answered 2011-02-15T20:39:19.423

Your Answer