Parallel.Foreach vs Foreach和Task in local variable

时间:2013-04-06 05:21:11

标签: c# parallel-processing task-parallel-library

当我们使用foreachTasks时,我们需要使用这样的局部变量:

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有什么区别吗?

1 个答案:

答案 0 :(得分:2)

你没有在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中的Parallel.ForEach和C#item中的foreach是两个非常不同的问题。

相关问题