9

does anyone know if there's any overload that would allow me to specify a step size in a Parallel.For loop? Samples in either c# or VB.Net would be great.

Thanks, Gonzalo

ckittel
  • 6,478
  • 3
  • 41
  • 71
Gonzalo
  • 679
  • 1
  • 8
  • 18

1 Answers1

15

Google for "enumerable.range step" and you should be able to come upon alternate implementations of Enumerable.Range that provide stepped ranges. Then you can just do a

Parallel.ForEach(BetterEnumerable.SteppedRange(fromInclusive, toExclusive, step), ...)

If google isn't working, implementation should be something like this:

public static class BetterEnumerable {
    public static IEnumerable<int> SteppedRange(int fromInclusive, int toExclusive, int step) {
        for (var i = fromInclusive; i < toExclusive; i += step) {
            yield return i;
        }
    }
}

Alternately if "yield return" gives one the heebie jeebies, you can always just create a regular old list in-place:

var list = new List<int>();
for (int i = fromInclusive; i < toExclusive; i += step) {
    list.Add(i);
}
Parallel.ForEach(list, ...);

This should be easily translatable to VB if that's a requirement.

Dax Fohl
  • 10,654
  • 6
  • 46
  • 90
  • Thanks Dax. Would it be too much extra work if i'm trying to do this in VB.Net where there's no yield return? – Gonzalo Aug 22 '11 at 02:18
  • No VB experience, but you should be able to use a for loop to make a List Of Integer with the integers you need, and then use `Parallel.ForEach` with that list. – Dax Fohl Aug 22 '11 at 02:32
  • @Gonzalo: The [async CTP](http://www.microsoft.com/download/en/details.aspx?id=22388) enables the use of iterators in VB.NET. – jason Aug 22 '11 at 03:11