为了账号安全,请及时绑定邮箱和手机立即绑定

这是 Partitioner.Create(int fromInclusive)

这是 Partitioner.Create(int fromInclusive)

C#
开心每一天1111 2023-07-22 16:32:42
我想我发现了该方法中的一个错误Partitioner.Create(int fromInclusive, int toExclusive)。rangeSize当范围超过 时,它会计算未提供的参数 的负值Int32.MaxValue。这是演示该问题的代码示例: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 =>  -178956971Range:  -178956971 =>  -357913941Range:  -357913941 =>  -536870911Range:  -536870911 =>  -715827881Range:  -715827881 =>  -894784851Range:  -894784851 => -1073741821Range: -1073741821 => -1252698791Range: -1252698791 => -1431655761Range: -1431655761 => -1610612731Range: -1610612731 => -1789569701Range: -1789569701 => -1968526671Range: -1968526671 => -2147483641Range: -2147483641 =>  2147483647因此,循环抛出这些范围for (int i = range.Item1; i < range.Item2; i++)将导致除最后一个范围之外的所有范围的零循环,这将有效地循环该Int32类型的整个范围。有一个特殊情况。下面的分区器计算 arangeSize为 1。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 Framework 的未来版本中修复该错误之前,您建议采用什么解决方法?
查看完整描述

2 回答

?
动漫人物

TA贡献1815条经验 获得超10个赞

看来整数溢出发生在除法 toExclusive - fromInclusive 上。

是的,看起来这是一个错误。

在 .NET Framework 的未来版本中修复该问题之前,您建议采用什么解决方法?

我建议将您的输入转换为long并调用该版本。它仍然存在类似的溢出错误,但如果您的原始输入是,int您绝对不会遇到溢出情况long


查看完整回答
反对 回复 2023-07-22
?
喵喵时光机

TA贡献1846条经验 获得超7个赞

这是一个错误,我已记录了一个问题,以便在 .NET Core 的未来版本中修复此问题https://github.com/dotnet/corefx/issues/40201

并且建议的解决方法也是正确的。只需将输入参数转换为 long 即可。


查看完整回答
反对 回复 2023-07-22
  • 2 回答
  • 0 关注
  • 99 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信