【发布时间】:2013-06-05 23:38:01
【问题描述】:
考虑以下代码示例,它创建一个可枚举的整数集合并并行处理:
using System.Collections.Generic;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
Parallel.ForEach(CreateItems(100), item => ProcessItem(item));
}
private static IEnumerable<int> CreateItems(int count)
{
for (int i = 0; i < count; i++)
{
yield return i;
}
}
private static void ProcessItem(int item)
{
// Do something
}
}
是否保证Parallel.ForEach() 生成的工作线程每个都获得不同的项目,或者是否需要一些围绕i 递增和返回的锁定机制?
【问题讨论】:
-
只使用 Enumerable.Range 。
-
@newStackExchangeInstance:我认为,这只是一个迭代器示例。
-
@newStackExchangeInstance:
Enumerable.Range()如何帮助我并行处理IEnumerable? -
顺便说一句,在这种特定情况下,使用
Parallel.For()可能更有意义。
标签: c# task-parallel-library ienumerable yield-return parallel.foreach