Powershell Workflow Processing

136 Views Asked by At

Why does this render a list in (almost) descending order?

Workflow FE-Parallel {
    foreach -parallel ($i in 0..100) { $i }
}

occasionally, there is a number out of order yet (0..100) produces a list starting at 0 and ending at 100.

1

There are 1 best solutions below

0
On BEST ANSWER

You can't guarantee the order that the items will be processed when you process them in parallel.

If you're asking why the sequence is not the same every time, or why it's not ascending from 0 through 100 in order, this is why. You could better see this with code like this:

foreach -parallel ($i in 0..100) {
    Start-Sleep -Milliseconds (Get-Random -Minimum 100 -Maximum 800)
    $i
}

If you're asking why it's descending (as opposed to seeming more "random") then I think that's an implementation detail. Internally, the code that sets up each thread (or runspace, or whatever mechanism is used) needs to iterate over each of the items. It likely does it in a predictable way, and when your operation is so straightforward, it's likely that they finish in roughly the same order.

Why would it do it in reverse? Not sure, but the important thing is that you cannot rely on any particular order.