下面例子使用Powershell線程運(yùn)行了兩個(gè)后臺(tái)任務(wù)和一個(gè)前臺(tái)任務(wù),創(chuàng)建幾個(gè)運(yùn)行時(shí)間長點(diǎn)的任務(wù),并且每個(gè)任務(wù)命令中添加使用Start-Sleep。
復(fù)制代碼 代碼如下:
$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
相繼執(zhí)行這3個(gè)任務(wù)從Start-Sleep中看至少需要花費(fèi)12秒。但是這個(gè)腳本僅執(zhí)行了5秒多一點(diǎn)。其結(jié)果保存為$result1, $result2和$result3。與后臺(tái)作業(yè)對(duì)比,它在返回大數(shù)據(jù)用時(shí)將差不多。
文章出處:http://www.pstips.net/
您可能感興趣的文章:- Powershell后臺(tái)作業(yè)、異步操作實(shí)例
- PowerShell快速創(chuàng)建一個(gè)指定大小文件的實(shí)例分享
- PowerShell 獲取系統(tǒng)信息的函數(shù)