4

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);
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
phogl
  • 494
  • 1
  • 8
  • 16

3 Answers3

5

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; });
James Kovacs
  • 11,549
  • 40
  • 44
  • yes, that works, but i hoped there was a more elegant version – phogl Nov 25 '10 at 19:12
  • Unfortunately Microsoft only supplies int and long versions of Parallel.For(). There is no generic Parallel.For(), where T is the range variable. To support ulong, you would have to modify their source code or write your own implementation of Parallel.For(). – James Kovacs Nov 25 '10 at 19:26
  • i think it will be the own implementation of parallel.for, but i fear it will not be equally efficient. – phogl Nov 25 '10 at 19:29
  • Mono has an open source implementation of the Parallel Extensions. I suspect that this would be a better starting point than rolling your own impl completely from scratch... http://tirania.org/blog/archive/2008/Jul-26-1.html – James Kovacs Nov 25 '10 at 19:47
  • This wont work if the init value of x is long.MinValue because long.MaxValue + (ulong)long.MinValue != 0 – AnGG Feb 25 '22 at 22:20
2

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);
}
VahidN
  • 18,457
  • 8
  • 73
  • 117
0

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);
});
AnGG
  • 679
  • 3
  • 9