为什么 ToList() 会进行排序?

问题描述 投票:0回答:1

当我执行以下代码时:

using static System.Console;

var numbers = ParallelEnumerable.Range(0, 50);

WriteLine("\nNumbers divisible by 5 are:");
var divisibleBy5 = numbers
    .AsParallel()
    .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
    .Where(x => x % 5 == 0);
   // .Where(x => x % 5 == 0)
   //.ToList();
foreach (var number in divisibleBy5)
{
    Write(number + "\t");
}

大多数时候我都能看到无序的结果。这是一个示例输出(预期行为):

Numbers divisible by 5 are:
0       15      30      40      5       20      35      45      10      25

现在我更改查询一点点(现在使用 ToList()):

var divisibleBy5 = numbers
    .AsParallel()
    .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
    //.Where(x => x % 5 == 0);
    .Where(x => x % 5 == 0)
   .ToList();

运行此更新后,我总是看到排序的输出:

Numbers divisible by 5 are:
0       5       10      15      20      25      30      35      40      45

问题:

1.这是预期的行为吗?

2.如果是这样,为什么?我们有这方面的支持文档吗?

我在这里缺少什么?可以分享一下你的想法吗?

c# .net-8.0 plinq tolist
1个回答
0
投票

如果您想按原始顺序接收结果,正确的做法是使用

AsOrdered
PLINQ 运算符:

ParallelQuery<int> divisibleBy5 = numbers
    .AsParallel()
    .AsOrdered()
    .Where(x => x % 5 == 0);

ToList
PLINQ 运算符可能会意外生成有序结果。这没有记录在案,而且它当然不是您应该依赖的东西(假设您的目标是编写一个始终正确运行的程序)。

© www.soinside.com 2019 - 2024. All rights reserved.