【发布时间】:2018-08-10 01:20:10
【问题描述】:
我正在尝试向函数内的全局数组添加一个值。函数调用是多线程的,会瞬间调用函数的多个实例
每个线程都会修改数组,但会覆盖其他线程写入的数据。
我的代码如下:
Function QuickPing {
param ($LastByte)
$P = New-Object -TypeName "System.Net.NetworkInformation.Ping"
if(($P.Send("200.200.200.$LastByte")).status -eq "success"){
echo "this one responded 200.200.200.$LastByte"
$global:alive+="200.200.200.$LastByte"
$global:alive
}
}
$global:alive = @()
1..255 | Start-Parallel -Command QuickPing -MaxThreads 500
write-host $alive
输出如下:
PS C:\WINDOWS\system32> E:\scripts_during_phase2\ping_array.ps1
this one responded 200.200.200.1
200.200.200.1
this one responded 200.200.200.17
200.200.200.17
this one responded 200.200.200.254
200.200.200.254
PS C:\WINDOWS\system32> $alive
PS C:\WINDOWS\system32>
如上所示,每次调用该函数时,$alive 数组中的值都会被覆盖。
当write-host $alive 命令运行时,我如何确保$alive 包含200.200.200.1,200.200.200.17,200.200.200.254
【问题讨论】:
-
Start-Parallel似乎是基于RunspaceFactory Class的自定义模块。实际上,设计*Remember that RunSpaces don’t share anything*中有一个明确的注释,这对于 RunSpaces 来说并不普遍,因为您可以与SessionStateProxy Class共享信息,但这显然没有在此解决方案中实现。
标签: .net windows multithreading function powershell