关于ulong的C#System.Threading.Tasks.Parallel.For

时间:2010-11-25 18:50:29

标签: c# for-loop parallel-processing ulong

在C#中,有一个System.Threading.Tasks.Parallel.For(...),它与for循环一样,没有顺序,但是在多个线程中。 问题是,它只适用于long和int,我想使用ulong。好的,我可以进行类型转换,但是边界有些麻烦。让我们说,我想要一个从long.MaxValue-10到long.MaxValue + 10的循环(记住,我说的是ulong)...我该怎么做? (我必须承认,我现在感觉有点愚蠢,但我现在无法理解)

一个例子:

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

2 个答案:

答案 0 :(得分:3)

您始终可以写信给Microsoft并要求他们将Parallel.For(ulong,ulong,Action&lt; ulong&gt;)添加到.NET Framework的下一个版本中。在此之前,你将不得不求助于这样的事情:

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

答案 1 :(得分:0)

或者您可以为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);
}