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

标签:
PowerShell,多线程

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
内蒙古资源网 Copyright www.nmgbbs.com

评论“PowerShell多线程执行前后台作业的例子”

暂无“PowerShell多线程执行前后台作业的例子”评论...

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。