2010-11-25 81 views
2

在C#中,这个System.Threading.Tasks.Parallel.For(...)它与for循环一样,没有顺序,但是在多个线程。 事情是,它只能在long和int上工作,我想和ulong一起工作。好吧,我可以改名,但我在边界上遇到了一些麻烦。比方说,我想要一个从long.MaxValue-10到long.MaxValue + 10的循环(请记住,我正在谈论ulong)......我该怎么做? (我必须承认,我觉得有点愚蠢的权利,但我不能算出它现在)C#System.Threading.Tasks.Parallel.For 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); 
} 

回答

3

您可以随时写信给微软,并要求他们将Parallel.For(ulong,ulong,Action <ulong>)添加到.NET Framework的下一个版本。在此之前,出来的时候,你就不得不求助于这样的事情:

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

是,这样的作品,但我希望有一个更优雅版本 – phogl 2010-11-25 19:12:50

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