Dmitry Bychenko answer this, but you can also implement your own ParallelFor with a custom step that will make your code a little more readable:
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); }
Here is the implementation of 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; } }
Then, for example, if you run the following code:
ParallelFor(3, 16, x => x + 2, Console.WriteLine);
You will get the following output (on separate lines, of course):
5, 11, 7, 13, 9, 15
source share