Parallel.Foreach与Foreach和局部变量中的Task [英] Parallel.Foreach vs Foreach and Task in local variable
问题描述
当我们使用foreach
和Tasks
时,我们需要使用这样的局部变量:
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());
但是Parallel.Foreach
呢,我像这样使用它:
But how about Parallel.Foreach
, I use it like this:
Parallel.ForEach(Source, (TargetType item) => DoSomething(item));
因此,您看不到任何局部变量.但是Parallel.Foreach
如何工作?不需要引入任何局部变量吗?或者,如果需要的话,我该如何定义它?
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?
更新
.NET 4和.NET 4.5有什么区别吗?
Is there any difference in .NET 4 and .NET 4.5?
推荐答案
您没有在Parallel.ForEach
中定义任何局部变量-item
仅仅是形式参数-Parallel.ForEach
的实现代码就是一个必须处理变量,以及变量是局部变量,捕获变量还是其他变量.
You do not define any local variable in Parallel.ForEach
- item
is nothing more than a formal parameter - the implementation code of Parallel.ForEach
is the one that will have to handle variables, and whether they are local, captured or something else.
无需定义与形式参数有关的局部变量Parallel.ForEach
-您的匿名委托的调用者代码将处理该变量并将其传递给您的函数.
There is no need to define a local variable related to the formal parameter Parallel.ForEach
- the caller code of your anonymous delegate will handle the variable and pass it to your function.
但是在C#4中,如果捕获另一个变量,则可能需要使用局部变量,即:
However in C#4, you might need to use a local variable if you capture another variable, that is:
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));
}
}
您可以看到上面的区别:localOtherItem
来自定义了匿名函数的上下文:称为闭包.而items
中的项目仅作为方法参数传递给匿名函数.
You can see the difference above: localOtherItem
is taken from the context where the anonymous function is defined: that is called a closure. Whereas the items in items
are passed simply as a method parameter to the anonymous function.
简而言之:Parallel.ForEach
中的item
和C#foreach
中的item
是两个非常不同的问题.
In short: the item
in Parallel.ForEach
and the item
in C# foreach
are two very different problems.
这篇关于Parallel.Foreach与Foreach和局部变量中的Task的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!