我想我在方法Partitioner.Create(int fromInclusive, int toExclusive)
中发现了一个错误。当范围超过Int32.MaxValue
时,它计算非预先参数rangeSize
的负值。这是一个代码示例,可说明问题:
var partitioner = Partitioner.Create(-1, Int32.MaxValue);
var partitions = partitioner.GetPartitions(1);
foreach (var partition in partitions)
{
while (partition.MoveNext())
{
var range = partition.Current;
Console.WriteLine($"Range: {range.Item1,11} => {range.Item2,11}");
}
}
输出:
Range: -1 => -178956971
Range: -178956971 => -357913941
Range: -357913941 => -536870911
Range: -536870911 => -715827881
Range: -715827881 => -894784851
Range: -894784851 => -1073741821
Range: -1073741821 => -1252698791
Range: -1252698791 => -1431655761
Range: -1431655761 => -1610612731
Range: -1610612731 => -1789569701
Range: -1789569701 => -1968526671
Range: -1968526671 => -2147483641
Range: -2147483641 => 2147483647
因此,用for (int i = range.Item1; i < range.Item2; i++)
掷出这些范围将导致除最后一个范围以外的所有范围有效地循环Int32
类型的全部范围。
有一个特殊情况。下面的分区计算1。
的rangeSize
Partitioner.Create(Int32.MinValue, Int32.MaxValue);
这是该方法的源代码:
public static OrderablePartitioner<Tuple<int, int>> Create(
int fromInclusive, int toExclusive)
{
// How many chunks do we want to divide the range into? If this is 1, then the
// answer is "one chunk per core". Generally, though, you'll achieve better
// load balancing on a busy system if you make it higher than 1.
int coreOversubscriptionRate = 3;
if (toExclusive <= fromInclusive) throw new ArgumentOutOfRangeException("toExclusive");
int rangeSize = (toExclusive - fromInclusive) /
(PlatformHelper.ProcessorCount * coreOversubscriptionRate);
if (rangeSize == 0) rangeSize = 1;
return Partitioner.Create(CreateRanges(fromInclusive, toExclusive, rangeSize),
EnumerablePartitionerOptions.NoBuffering); // chunk one range at a time
}
似乎在删除toExclusive - fromInclusive
上发生整数溢出。
如果这确实是一个错误,则您建议使用什么解决方法,直到将来在.NET框架的未来版本中修复?
看来,整数溢出发生在分隔线上 - 来自包含。
是的,看起来好像是一个错误。
您建议什么解决方法,直到将来将其固定在将来的版本中 .NET框架?
我建议将您的输入投入long
并改用该版本。它仍然具有类似的溢出错误,但是如果您的原始输入是int
,则绝对不会使用long
遇到溢出方案。
@mjwills是正确的。
这是一个错误,我已经记录了一个问题,以在.net core https://github.com/dotnet/corefx/issues/40201
的将来解决此问题。建议的解决方法也是正确的。只需将输入参数投入长时间。