加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:19:18 所属栏目:百科 来源:网络整理
导读:.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的好文章.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读