4

I have a collection of Model classes and I wan't to Map each class individually to View Model classes.

I can use Parallel.ForEach or ParallelEnumerable.ForAll, so what is the difference between the 2, if any?

I couldn't find anything on MSDN.

Stan R.
  • 15,757
  • 4
  • 50
  • 58

1 Answers1

7

I can use Parallel.ForEach or ParallelEnumerable.ForAll, so what is the difference between the 2, if any?

Parallel.ForEach is the equivelent to using foreach in normal code.

The ParallelEnumerable.ForAll method is effectively the equivelent to List<T>.ForEach.

Both will perform and work similarly, though the ForAll method requires you to be using PLINQ already, as you need a ParallelEnumerable. Parallel.ForEach works directly off any IEnumerable<T>.

In general, I tend to prefer Parallel.ForEach, as the sole purpose of ForAll is to cause side effects. There are some disadvantages to this, as described in detail by Eric Lippert.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • uh huh, so basically they are pretty much identical except for the fact that `ParallelEnumerable` requires an actual `ParallelEnumerable`. – Stan R. Jun 06 '13 at 23:58
  • I agree with the side-effect part, but I want to map items in parallel in this case I think it is valid to do so. Correct me if I am wrong, but `Parallel.ForEach` does indeed execute iterations in parallel...right? – Stan R. Jun 07 '13 at 00:00
  • @StanR. Yes, it does. "Mapping" suggests a PLINQ Select() clause, not a `ForAll()` statement, though, as Select is effectively a mapping operation... – Reed Copsey Jun 07 '13 at 00:01
  • 2
    I think I am wasting time here, since i would have to collect all my mapped items back into a concurrent list probably not worth it for a small list in terms of context switching. – Stan R. Jun 07 '13 at 00:05
  • @StanR. Depends on the # and what you're doing with the mapping - if you're building the queue, and processing is required, you can construct it directly from the PLINQ.Select() results via http://msdn.microsoft.com/en-us/library/dd267303.aspx – Reed Copsey Jun 07 '13 at 00:10
  • i would say that if each mapping procedure took a decent amount of time, it would make sense. but this is simple property mappings on less than 1000 items. pure overkill in my opinion :) thanks for the linq, i need to step up my PLINQ game. – Stan R. Jun 07 '13 at 00:16