Understanding TPL Data Flow Degree Parallelism Order

I read Dataflow (Task Parallel Library) , and there is a part that reads:

When you specify a maximum degree of parallelism that is greater than 1, multiple messages are processed simultaneously, and therefore messages may not be processed in the order in which they were received. However, the order in which messages are output from the block will be properly ordered.

What does it mean?

For example, I set my action block with a degree of parallelism = 5:

testActionBlock = new ActionBlock<int>(i => Consumer(i), new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = 5 }); await Producer(); testActionBlock.Completion.Wait(); 

My Producer () basically puts numbers in a block:

 private async Task Producer() { for (int i=0; i<= 1000; i++) { await testActionBlock.SendAsync(i); } testActionBlock.Complete(); } 

And my consumer (i) just writes the lines:

 private async Task Consumer(int i) { if (i == 1) { await Task.Delay(5000); } Console.WriteLine(i); } 

Does this mean that Consumer (2) will be blocked until processing by Consumer (1) is completed (since there is a 5 second delay)? I tested the code, and it doesn't seem to be that way. Even when I removed the delay of 5 seconds, I do not see that the result was in order.

[Update]

 bBlock = new BufferBlock<int>(option); testActionBlock = new ActionBlock<int>(i => Consumer(i), new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = 5 }); bBlock.LinkTo(testActionBlock); await Producer(); testActionBlock.Completion.Wait(); 

My Producer () will now add to bBlock:

 private async Task Producer() { for (int i=0; i<= 1000; i++) { await bBlock.SendAsync(i); } bBlock.Complete(); } 

So, in this case, Consumer (1) will wait 5 seconds before consumer (2) can continue?

+5
source share
1 answer

No. DoP, which you can think of as threads (not really, but an easy way to think about it)

So, at 5, he will try to process 5 at a time. Since # 1 takes 5 seconds, # 2 will certainly end first. This will probably be # 3, # 4 and # 5. Probably even # 6 (starting with # 2, DoP will let him start C # 6)

Even without delays, there is no guaranteed order for processing. Therefore, never depend on the ORDER WHICH THEY FULFILL. Having said that, when you use message outputs (DO NOT write out, since this is the order they follow), they will be reordered in the order in which they entered, although they are executed in random order.

+3
source

All Articles