Question

In C#, theres a System.Threading.Tasks.Parallel.For(...) wich 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? (I must admit, I feel a little stupid right now, but I just can't figure it out right now)

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);
}
Was it helpful?

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; });

OTHER TIPS

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top