31. PowerShell -- 多線程執行前後台作業

來源:互聯網
上載者:User

標籤: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 -- 多線程執行前後台作業

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.