.NET Framework使得并行聚合变得容易,但根据
the documentation,它仅适用于可交换操作,即f(x,y)= f(y,x)的操作:
The .NET implementation of the Parallel Aggregation pattern also expects the operations to be commutative.
我想使用串联聚合字符串值,这是一种非交换操作.顺序方法如下所示:
var result = string.Concat(sequence.Select(this.LongOperation));
所以如果this.LongOperation连续返回Hello,World和!,最终结果是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,Value = this.LongOperation(c.Value)) .OrderBy(c => c.Index) .Select(c => c.Value); var result = string.Concat(parts);
我希望这样做,还是有更简单的方法来做这件事?
解决方法
你在找
ParallelEnumerable.AsOrdered
:
var result = sequence .AsParallel() .AsOrdered() .Aggregate(seed: string.Empty,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,current) => prev + current); Console.WriteLine(result);
并行编程团队有一篇关于PLINQ Ordering的好文章.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。