有一种简单的方法可以使用非交换操作进行并行聚合吗?

时间:2015-08-26 12:29:59

标签: c# linq parallel-processing aggregate

.NET Framework使得并行聚合变得容易,但根据the documentation,它仅适用于可交换操作,即 f x y )= f y x ):

  

并行聚合模式的.NET实现也期望操作是可交换的。

我想使用串联聚合字符串值,这是一种非交换操作。顺序方法如下所示:

var result = string.Concat(sequence.Select(this.LongOperation));

因此,如果this.LongOperation连续返回HelloWorld!,则最终结果为HelloWorld!

如果我使用并行聚合,结果可能是HelloWorld,还有World!Hello!HelloWorld等。

解决方法是做类似的事情:

var result = sequence
    .AsParallel()
    .Select((v, i) => new { Index = i, Value = v })
    .Select(c => new { Index = c.Index, Value = this.LongOperation(c.Value))
    .OrderBy(c => c.Index)
    .Aggregate(seed: string.Empty, func: (prev, current) => prev + current);

(不重要,在我的特定情况下)缺点是,无论如何都要在OrderBy步骤评估整个序列,而不等到聚合。写这个的另一种方法是:

var parts = sequence
    .AsParallel()
    .Select((v, i) => new { Index = i, Value = v })
    .Select(c => new { Index = c.Index, Value = this.LongOperation(c.Value))
    .OrderBy(c => c.Index)
    .Select(c => c.Value);

var result = string.Concat(parts);

我希望这样做,还是有更简单的方法来做这件事?

1 个答案:

答案 0 :(得分:1)

您正在寻找ParallelEnumerable.AsOrdered

var result = sequence
    .AsParallel()
    .AsOrdered()
    .Aggregate(seed: string.Empty, func: (prev, current) => prev + current);

您需要保留排序的事实会对您的查询产生性能影响。由于结果需要按顺序聚合,您不会享受并行性的最大好处,并且有时可能导致性能降低而不是顺序迭代。话虽如此,这将完成你所追求的目标。

例如,以下代码将始终如一地生成"[7][35][22][6][14]"

var result = new [] { 35, 14, 22, 6, 7 }
    .AsParallel()
    .AsOrdered()
    .Select(c => "[" + c + "]")
    .Aggregate(seed: string.Empty, func: (prev, current) => prev + current);

Console.WriteLine(result);

并行编程团队有一篇关于PLINQ Ordering的好文章。

相关问题