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

c# – 有一种简单的方法可以使用非交换 *** 作进行并行聚合吗?,第1张

概述.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. 我想使用串联聚合字符串值,这是 .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的好文章.

总结

以上是内存溢出为你收集整理的c# – 有一种简单的方法可以使用非交换 *** 作进行并行聚合吗?全部内容,希望文章能够帮你解决c# – 有一种简单的方法可以使用非交换 *** 作进行并行聚合吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1231597.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存