当我们使用foreach和Tasks时,我们需要使用如下的局部变量:
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呢,我用它是这样的:
Parallel.ForEach(Source, (TargetType item) => DoSomething(item));因此没有任何局部变量,正如您所看到的。但是Parallel.Foreach是如何工作的呢?是否需要引入任何局部变量?或者,如果需要,我如何定义它?
更新
.NET 4和.NET 4.5有什么不同吗?
发布于 2013-04-06 11:19:18
您不需要在Parallel.ForEach中定义任何局部变量-- item只不过是一个正式的参数-- Parallel.ForEach的实现代码需要处理变量,无论它们是局部变量、捕获变量还是其他变量。
不需要定义与形式参数Parallel.ForEach相关的局部变量--匿名委托的调用方代码将处理该变量并将其传递给您的函数。
但是,在C#4中,如果捕获另一个变量,即:
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中的项只是作为方法参数传递给匿名函数。
简而言之:item In Parallel.ForEach和item in C# foreach是两个截然不同的问题。
https://stackoverflow.com/questions/15847329
复制相似问题