Search code examples
c#for-loopparallel-processingparallel.forulong

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

  • You can always write to Microsoft and ask them to add Parallel.For(ulong, ulong, Action<ulong>) to the next version of the .NET Framework. Until that comes out, you'll have to resort to something like this:

    Parallel.For(-10L, 10L, x => { var index = long.MaxValue + (ulong) x; });