【发布时间】:2021-06-21 08:44:22
【问题描述】:
如果我理解PowerShell Scopes documentation,应该可以从使用Start-ThreadJob 启动的线程分配给$using 范围变量。文档说(强调我的):
Using范围修饰符在以下上下文中受支持:
- ...
- 线程作业,通过
Start-ThreadJob或ForEach-Object -Parallel启动(单独的线程会话)根据上下文,嵌入的变量值要么是调用者范围内数据的独立副本,要么是对其的引用。
...
在线程会话中,它们通过引用传递。这意味着可以在不同的线程中修改调用范围变量。要安全地修改变量需要线程同步。
但以下运行失败:
$foo = 1
Start-ThreadJob {
Write-Host $using:foo
$using:foo = 2
} | Wait-Job | Out-Null
Write-Host $foo
$using:foo = 2 出现错误:
赋值表达式无效。赋值运算符的输入必须是能够接受赋值的对象,例如变量或属性。
使用Write-Host $using:foo 打印变量可以正常工作。
我使用的是 PowerShell 7.1。
【问题讨论】:
标签: multithreading powershell scope powershell-core powershell-jobs