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?