標籤:powershell 多線程
使用後台作業執行多個任務從先前的技巧中看不是非常高效,它在處理每個後台作業返回結果時將會浪費很多效能。一個更有效方法是使用進程內的任務。他能分別單獨的執行任務與Powershell類似,所以它不是按順序傳回值的。
下面例子使用Powershell線程運行了兩個背景工作和一個前台任務,建立幾個已耗用時間長點的任務,並且每個任務命令中添加使用Start-Sleep。
代碼如下:
$start = Get-Date
$task1 = { Start-Sleep -Seconds 4; Get-Service }
$task2 = { Start-Sleep -Seconds 5; Get-Service }
$task3 = { Start-Sleep -Seconds 3; Get-Service }
# run 2 in separate threads, 1 in the foreground
$thread1 = [PowerShell]::Create()
$job1 = $thread1.AddScript($task1).BeginInvoke()
$thread2 = [PowerShell]::Create()
$job2 = $thread2.AddScript($task2).BeginInvoke()
$result3 = Invoke-Command -ScriptBlock $task3
do { Start-Sleep -Milliseconds 100 } until ($job1.IsCompleted -and $job2.IsCompleted)
$result1 = $thread1.EndInvoke($job1)
$result2 = $thread2.EndInvoke($job2)
$thread1.Runspace.Close()
$thread1.Dispose()
$thread2.Runspace.Close()
$thread2.Dispose()
$end = Get-Date
Write-Host -ForegroundColor Red ($end - $start).TotalSeconds
相繼執行這3個任務從Start-Sleep中看至少需要花費12秒。但是這個指令碼僅執行了5秒多一點。其結果儲存為$result1, $result2和$result3。與後台作業對比,它在返回大資料用時將差不多。
文章出處:http://www.pstips.net/
本文出自 “Ricky's Blog” 部落格,請務必保留此出處http://57388.blog.51cto.com/47388/1643899
31. PowerShell -- 多線程執行前後台作業