Parallel.Foreach vs Foreach and Task in a local variable

When we use foreach and Tasks , we need to use local variables such as 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 what about Parallel.Foreach , I use it as follows:

 Parallel.ForEach(Source, (TargetType item) => DoSomething(item)); 

So there is no local variable as you see. But how does Parallel.Foreach work? No need to enter any local variables? or, if necessary, how can I determine it?

UPDATE

Is there a difference in .NET 4 and .NET 4.5?

+1
c # parallel-processing task-parallel-library
source share
1 answer

You do not determine which local variable in Parallel.ForEach - item is nothing more than a formal parameter - the implementation code of Parallel.ForEach is the one that will process the variables and whether they will be local, captured, or something else.

There is no need to define a local variable associated with the formal parameter Parallel.ForEach - the caller code of your anonymous delegate processes the variable and passes it to your function.

However, in C # 4, you may need to use a local variable if you capture another variable, namely:

 void DoSomething(ItemType item, OtherType other) { } void YourFunction(IEnumerable<ItemType> items, IEnumerable<OtherType> others) { foreach (var otherItem in others) { var localOtherItem = otherItem; Parallel.ForEach(items, item => DoSomething(item, localOtherItem)); } } 

You can see the difference above: localOtherItem is taken from the context where the anonymous function is defined: this is called a closure. While items in items are passed simply as a parameter to a method of an anonymous function.

In short: item in Parallel.ForEach and item in C # foreach are two very different problems.

+2
source share

All Articles