2

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.

enter image description here

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.

enter image description here

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 ?

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118

1 Answers1

2

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
ASh
  • 34,632
  • 9
  • 60
  • 82
  • i feel so stupid now. any way this is perfect! thanks a lot. – M.kazem Akhgary Nov 23 '15 at 11:32
  • 1
    @M.kazemAkhgary, thanks. i have been experimenting with this sample. method demonstrates interesting behavior, if some tasks take longer time than others, e.g: `if (i%5 != 0) Task.Delay(1000).Wait(); else Task.Delay(20000).Wait();` – ASh Nov 23 '15 at 11:42
  • i came from [here](http://stackoverflow.com/questions/33394310/executing-n-number-of-threads-in-parallel-and-in-a-sequential-manner). The good answer has been posted by [usr](http://stackoverflow.com/a/33394444/4767498) but it wasnt accepted. im pretty sure OP had this problem – M.kazem Akhgary Nov 23 '15 at 12:00