Dmitry Bychenko 的答案明白了,但您也可以使用自定义步骤实现自己的 ParallelFor,这将使您的代码更具可读性:
static void ParallelFor(int start, int last, Func<int, int> step, Action<int> action)
{
var enumerable = StepEnumerable<int>
.Create(start, step)
.TakeWhile(x => x < last);
Parallel.ForEach(enumerable, action);
}
这是StepEnumerable的实现:
public class StepEnumerator<T> : IEnumerator<T>
{
...
public StepEnumerable(T value, Func<T, T> manipulation)
{
mEnumerator = new StepEnumerator<T>(value, manipulation);
}
public static StepEnumerable<T> Create(T value, Func<T, T> manipulation)
{
return new StepEnumerable<T>(value, manipulation);
}
...
}
public class StepEnumerator<T> : IEnumerator<T>
{
public bool MoveNext()
{
Current = mManipulation(Current);
return true;
}
}
然后,例如,如果您运行以下代码:
ParallelFor(3, 16, x => x + 2, Console.WriteLine);
您将获得以下输出(当然是在单独的行中):
5、11、7、13、9、15