When we use foreach and Tasks we need to use local variables like this:
List<Task> TaskPool = new List<Task>(); foreach (TargetType Item in Source) { TargetType localItem = Item; TaskPool.Add(Task.Factory.StartNew(() => DoSomething(localItem))); } Task.WaitAll(TaskPool.ToArray()); But how about Parallel.Foreach, I use it like this:
Parallel.ForEach(Source, (TargetType item) => DoSomething(item)); So there is not any Local Variable as you see. But how does Parallel.Foreach work? Is there no need to introduce any local variables? or if needed, how can I define it?
UPDATE
Is there any difference in .NET 4 and .NET 4.5?
foreachandParallel.foreach? if yes? so how about .NET 4?foreachloop (I'd sayParallel.ForEachis a method call not a loop). In C# 4 it is necessary. I would also note this is compiler behavior, not runtime behavior. This is a "breaking" change from previous compiler versions. See blogs.msdn.com/b/ericlippert/archive/2009/11/12/…