Ordered Parallel is not working as expected. (Convert List into IEnumerable?)

ε祈祈猫儿з 提交于 2019-12-24 05:15:07

问题


I have a list of works to do. and i want to run them in parallel in an ordered way. but ordered parallel is trying to split methods into chunks and then execute chunks in ordered way.

Here is the reproduced problem.

var list = Enumerable.Range(0, 1000).ToList();

list.AsParallel().AsOrdered().ForAll(i =>
{
    Task.Delay(1000).Wait();
    Console.WriteLine(i);
});

I expect this to first print values from start. like or something like this

1
0
2
3

But here is the results.

This means ordered parallel is dividing list into chunks and starts executing them in order. but i dont want this to execute tasks from middle of list. How can i fix this behavior?

I noticed if i dont use List and instead use IEnumerable it fixes the problem and prevents splitting. I think its because the Enumerable does not hold the all values yet so dividing is not possible.

var list = Enumerable.Range(0, 1000); // removed ToList

The results will change to this which is what i want.

But i have populated a list. i dont have pure ienumerable how ever i tried

list.AsEnumerable().AsParallel().AsOrdered()....

But parallel still starts to split the list. Is there any parallel option to avoid this?

If not the question may change to how to explicitly convert List into Enumerable? here list.AsEnumerable() still seems to be potentially list. how to get pure enumerable ?


回答1:


looks like you can achive the required effect simpler:

var list = Enumerable.Range(0, 1000).ToList();

list
.Select(x=>x)  // !
.AsParallel().AsOrdered().ForAll(i =>
{
    Task.Delay(1000).Wait();
    Console.WriteLine(i);
});


list.AsEnumerable() is not a potentially list, but list itself
var L = list.AsEnumerable();
bool e = ReferenceEquals(L, list);
// e is True, they are same objects


来源:https://stackoverflow.com/questions/33869830/ordered-parallel-is-not-working-as-expected-convert-list-into-ienumerable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!