Performing multiple tasks with a background job is not very efficient from the previous techniques, and it wastes a lot of performance when it comes to processing each background job's return results. A more efficient approach is to use in-process tasks. His ability to perform separate tasks is similar to PowerShell, so it does not return values sequentially.
The following example uses a PowerShell thread to run two background tasks and a foreground task, create several long-running tasks, and add the use of Start-sleep to each task command.
The code is 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 successively 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 background jobs, it will be similar when returning big data.
Article Source: http://www.pstips.net/
This article comes from the "Ricky's blog" blog, please be sure to keep this source http://57388.blog.51cto.com/47388/1643899
PowerShell-Multi-threaded execution before and after work