下面例子使用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/

您可能感兴趣的文章:

声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。