'Parallel.For with 64-bit unsigned indexes (UInt64)

In C#, there's a System.Threading.Tasks.Parallel.For(...) which does the same as a for loop, without order, but in multiple threads. The thing is, it works only on long and int, I want to work with ulong. Okay, I can typecast but I have some trouble with the borders.

Let's say, I want a loop from long.MaxValue-10 to long.MaxValue+10 (remember, I'm talking about ulong). How do I do that?

An example:

for (long i = long.MaxValue - 10; i < long.MaxValue; ++i)
{
    Console.WriteLine(i);
}
//does the same as
System.Threading.Tasks.Parallel.For(long.MaxValue - 10, long.MaxValue, delegate(long i)
{
    Console.WriteLine(i);
});
//except for the order, but theres no equivalent for
long max = long.MaxValue;
for (ulong i = (ulong)max - 10; i < (ulong)max + 10; ++i)
{
    Console.WriteLine(i);
}


Solution 1:[1]

Or you can create a custom range for Parallel.ForEach

public static IEnumerable<ulong> Range(ulong fromInclusive, ulong toExclusive)
{
  for (var i = fromInclusive; i < toExclusive; i++) yield return i;
}

public static void ParallelFor(ulong fromInclusive, ulong toExclusive, Action<ulong> body)
{
  Parallel.ForEach(
     Range(fromInclusive, toExclusive),
     new ParallelOptions { MaxDegreeOfParallelism = 4 },
     body);
}

Solution 2:[2]

This will work for every long value from long.MinValue inclusive to long.MaxValue exclusive

Parallel.For(long.MinValue, long.MaxValue, x =>
{
    ulong u = (ulong)(x + (-(long.MinValue + 1))) + 1;
    Console.WriteLine(u);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VahidN
Solution 2 AnGG