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?