我有一组字符串,我需要执行两个操作.
第一个可以安全地以任何顺序(yay)独立处理,但是输出必须按原始顺序顺序处理(boo).
下面的Plinq让我大部分都在那里:
myStrings.AsParallel().AsOrdered()
.Select( str => Operation1(str) )
.AsSequential()
.Select( str => Operation2(str) );
//immagine Operation2() maintains some sort of state and must take the outputs from Operation1 in the original order
Run Code Online (Sandbox Code Playgroud)
这让我大部分都在那里,但问题是因为AsOrdered(),Operation1首先在每个字符串上执行,然后结果元素被排序回原始顺序,最后Operation2开始执行.
理想情况下,只要第一个字符串(即myStrings [0],而不是返回的第一个字符串)由Operation1调用返回,我就希望Operation2开始工作.
所以这是我试图解决这个问题的一般方法:
public static class ParallelHelper
{
public static IEnumerable<U> SelectAsOrdered<T, U>(this ParallelQuery<T> query, Func<T, U> func)
{
var completedTasks = new Dictionary<int, U>();
var queryWithIndexes = query.Select((x, y) => new { Input = x, Index = y })
.AsParallel()
.Select(t => new { Value …Run Code Online (Sandbox Code Playgroud)