The following example runs two background tasks and one foreground task using the PowerShell thread, creates several long-running tasks, and adds the use of Start-sleep to each task command.
Copy Code code as follows:
$start = Get-date
$task 1 = {Start-sleep-seconds 4; Get-service}
$task 2 = {Start-sleep-seconds 5; Get-service}
$task 3 = {Start-sleep-seconds 3; Get-service}
# run 2 in separate threads, 1 in the foreground
$thread 1 = [Powershell]::create ()
$job 1 = $thread 1. Addscript ($task 1). BeginInvoke ()
$thread 2 = [Powershell]::create ()
$job 2 = $thread 2. Addscript ($task 2). BeginInvoke ()
$result 3 = Invoke-command-scriptblock $task 3
do {start-sleep-milliseconds} until ($job 1. Iscompleted-and $job 2. iscompleted)
$result 1 = $thread 1. EndInvoke ($job 1)
$result 2 = $thread 2. EndInvoke ($job 2)
$thread 1. Runspace.close ()
$thread 1. Dispose ()
$thread 2. Runspace.close ()
$thread 2. Dispose ()
$end = Get-date
Write-host-foregroundcolor Red ($end-$start). TotalSeconds
It takes at least 12 seconds to perform these 3 tasks sequentially from Start-sleep. But this script only executes a little more than 5 seconds. The results are saved as $RESULT1, $result 2 and $RESULT3. Compared to a background job, it will be similar when returning large data.
The source of the article: http://www.pstips.net/