🎓 A1Learner
🔍
0 of 46 lessons completed

PowerShell Thread Jobs

A thread job is a background job that runs on a thread in the same process. It runs in the same process, so it starts quickly and shares the session.

One thread job doubles a number

Start-ThreadJob starts the block on a thread. Receive-Job with Wait collects its result.

$j = Start-ThreadJob -ScriptBlock { 21 * 2 }
$r = Receive-Job $j -Wait
"Thread job: $r"

A thread job takes a value

ArgumentList carries a value into the block. The block adds ten to the value it receives.

$j = Start-ThreadJob -ScriptBlock { param($x) $x + 10 } -ArgumentList 5
$r = Receive-Job $j -Wait
"Thread value: $r"

Several thread jobs are sorted

Each number starts its own thread job. Sorting the collected results gives a fixed order.

$jobs = @()
foreach ($n in 1..3) { $jobs += Start-ThreadJob -ScriptBlock { param($x) $x * 2 } -ArgumentList $n }
$out = Receive-Job $jobs -Wait | Sort-Object
"Thread jobs: " + ($out -join ", ")

Example

$jobs = @()
foreach ($n in 1..4) { $jobs += Start-ThreadJob -ScriptBlock { param($x) $x * $x } -ArgumentList $n }
$out = Receive-Job $jobs -Wait | Sort-Object
"Thread squares: " + ($out -join ", ")

Key points

  • Thread job: a background job that runs on a thread in the same process.
  • Thread: a small path of work inside one process.
  • Use Start-ThreadJob to start a thread job from a block.
  • Use Receive-Job with Wait to collect a thread job result.
  • Use Sort-Object on several thread job results because they finish in no fixed order.

In this example, four thread jobs are started, one for each number. Each block squares its own number. Receive-Job collects every result, and sorting gives a fixed printed order.

Note

Start-ThreadJob comes from the ThreadJob module, which is present on this platform.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What makes a thread job different from a separate process job?