Parallel.For where i does not go to i++

,
April 25, 2010 / 1 Comment

A problem was recent posed that I hadn’t thought to do using Parallel.For in C#. How do you parallelize a for loop variable increased by something other than i++? Typically, I would simply iterate over a enumerable collection and run against the data in parallel using Parallel.For and Parallel.ForEach.

It turns out that there is no support for this in the PFX API. Parallel.For does not support incrementing other than one and it does not support reverse iteration. Also, Enumerable is a static class – which means we can’t do extension methods on Enumerable. However, we can use a custom iterator to generate the sequence for us. By using a Func<int, int> allows us to use our familiar i+= syntax for the increment function. We can quickly create a very simple iterator that will help us out.

AUTHOR: CATEGORY: .Net, Headlines, LINQ