Parallel.ForEach vs Task.Factory.StartNew?

The first is a much better option Parallel. ForEach, internally, uses a Partitioner Parallel. ForEach(items, item => DoSomething(item))) By doing this, you still take advantage of the partitioners, but don't block until the operation is complete.

The first is a much better option. Parallel. ForEach, internally, uses a Partitioner to distribute your collection into work items.It will not do one task per item, but rather batch this to lower the overhead involved.

The second option will schedule a single Task per item in your collection. While the results will be (nearly) the same, this will introduce far more overhead than necessary, especially for large collections, and cause the overall runtimes to be slower. FYI - The Partitioner used can be controlled by using the appropriate overloads to Parallel.

ForEach, if so desired. For details, see Custom Partitioners on MSDN. The main difference, at runtime, is the second will act asynchronous.

This can be duplicated using Parallel. ForEach by doing: Task.Factory. StartNew( () => Parallel.

ForEach(items, item => DoSomething(item))); By doing this, you still take advantage of the partitioners, but don't block until the operation is complete.

2 IIRC, the default partitioning done by Parallel. ForEach also takes into account the number of hardware threads available, saving you from having to work out the optimum number of Tasks to start. Check out Microsoft's Patterns of Parallel Programming article; it's got great explanations of all of this stuff in it.

– Mal Ross Feb 17 at 14:37 @Mal: Sort of... That's actually not the Partitioner, but rather the job of the TaskScheduler. The TaskScheduler, by default, uses the new ThreadPool, which handles this very well now. – Reed Copsey Feb 17 at 16:42 Thanks.

I knew I should've left in the "I'm no expert, but..." caveat. :) – Mal Ross Feb 17 at 17:05.

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.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions