Starting a background job and printing its result
In order to pretend that this is a difficult calculation, the job uses
start-sleep
so that the job is not immediately finished.
After starting the job, the script goes on to do an unrelated task. Every once in a while, it checks the background job's state. If it has finished ($job.state -eq 'Completed
) and there is a result ($job.hasMoreData
), it collects the result and prints it:
$job = start-job {
#
# Calculate the 17th triangular number.
#
$result = 0;
foreach ($i in 1 .. 17) {
$result += $i
}
return $result
#
# Pretend it's a real difficult calculation that
# takes some time …
#
start-sleep 6
return $result
}
foreach ($j in 1 .. 10) {
#
# Do something different while the
# calculation runs in the background
#
write-host "j = $j"
if ($job.state -eq 'Completed') {
if ($job.hasMoreData) {
$t17 = receive-job $job
write-host "Calculated result = $t17"
}
}
start-sleep 2
}