随笔 - 911  文章 - 5  评论 - 94  阅读 - 243万

并行执行

 

复制代码
 1 $throttleLimit = 4
 2 $SessionState = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
 3 $Pool = [runspacefactory]::CreateRunspacePool(1, $throttleLimit, $SessionState, $Host)
 4 $Pool.Open()
 5 
 6 $id = 3
 7 $ScriptBlock = {
 8 #此处参数顺序要注意前后,AddArgument的第一个参数会被传递给$id,AddArgument的第二个参数会被传递给$x,与AddArgument的顺序无关,只与param的顺序有关
 9 param($id,$x)
10 #在此处定义需要执行的代码
11 Start-Sleep -Seconds 1
12 "Done processing ID $id"
13 "hello, $x"
14 }
15 
16 $threads = @()
17 #此处定义需要并行执行的进程总数($x)
18 $handles = for ($x = 1; $x -le 20; $x++) {
19 $powershell = [powershell]::Create().AddScript($ScriptBlock).AddArgument($id).addargument($x)
20 $powershell.RunspacePool = $Pool
21 $powershell.BeginInvoke()
22 $threads += $powershell
23 }
24 
25 do {
26 $i = 0
27 $done = $true
28 foreach ($handle in $handles) {
29 if ($handle -ne $null) {
30 if ($handle.IsCompleted) {
31 $threads[$i].EndInvoke($handle)
32 $threads[$i].Dispose()
33 $handles[$i] = $null
34 } else {
35 $done = $false
36 }
37 }
38 $i++
39 }
40 if (-not $done) { Start-Sleep -Milliseconds 500 }
41 } until ($done)
复制代码

 

posted on   momingliu11  阅读(654)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2013-05-28 wim封装到iso
2013-05-28 正则表达式2
2013-05-28 正则表达式
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示