gpt4 book ai didi

c# - RunSpacePool如何传递共享变量?

转载 作者:行者123 更新时间:2023-12-03 01:11:28 27 4
gpt4 key购买 nike

我正在尝试创建一个线程,该线程将使用共享变量(在主 session 和线程之间),并赋予线程使用主代码中外部函数的能力

我已经设法通过函数供线程使用,并且我已经设法通过了只读变量。我的问题是,如果我在线程内更改变量的值,然后尝试从主 session 读取它-我看不到值的更改,因此无法共享。

我怎么做?我的目标是最终拥有一个线程。

这是我的代码:

$x = [Hashtable]::Synchronized(@{})
$global:yo
Function ConvertTo-Hex {
#Write-Output "Function Ran"
write-host "hi"
$x.host.ui.WriteVerboseLine("===========")
write-host $yo
$global:yo = "test"
write-host $yo
}
#endregion



ls
# create an array and add it to session state
$arrayList = New-Object System.Collections.ArrayList
$arrayList.AddRange(('a','b','c','d','e'))
$x.host = $host
$sessionstate = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
$sessionstate.Variables.Add((New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry('arrayList', $arrayList, $null)))
$sessionstate.Variables.Add((New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry('x', $x, $null)))
$sessionstate.Variables.Add((New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry('yo', $yo, $null)))
$sessionstate.Commands.Add((New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry -ArgumentList 'ConvertTo-Hex', (Get-Content Function:\ConvertTo-Hex -ErrorAction Stop)))
$runspacepool = [runspacefactory]::CreateRunspacePool(1, 2, $sessionstate, $Host)
$runspacepool.Open()

$ps1 = [powershell]::Create()
$ps1.RunspacePool = $runspacepool

$ps1.AddScript({
for ($i = 1; $i -le 15; $i++)
{
$letter = Get-Random -InputObject (97..122) | % {[char]$_} # a random lowercase letter
$null = $arrayList.Add($letter)
start-sleep -s 1
}
})

# on the first thread start a process that adds values to $arrayList every second
$handle1 = $ps1.BeginInvoke()

# now on the second thread, output the value of $arrayList every 1.5 seconds
$ps2 = [powershell]::Create()
$ps2.RunspacePool = $runspacepool

$ps2.AddScript({
Write-Host "ArrayList contents is "
foreach ($i in $arrayList)
{
Write-Host $i -NoNewline
Write-Host " " -NoNewline
}
Write-Host ""
$global:yo = "BAH"
ConvertTo-Hex
})


1..2 | % {
$handle2 = $ps2.BeginInvoke()
if ($handle2.AsyncWaitHandle.WaitOne())
{
$ps2.EndInvoke($handle2)
}
start-sleep -s 1.5
write-host "====================" + $yo
}
write-host $yo

最佳答案

同步哈希表将满足您的需求:

# Sync'd hash table is accessible between threads
$hash = [HashTable]::Synchronized(@{})
$hash.Parameter = "Value"

有几种方法可以将其传递给新线程,我更喜欢简单的方法:
[PowerShell]$powershell = [PowerShell]::Create()
$powershell.AddScript({
Param
(
$hash
)
# do stuff
}).AddParameter("hash", $hash)

$powershell.BeginInvoke()

您从任一线程对哈希表执行的任何操作都将对两个线程(以及您传递给该线程的任何其他数量)均可见并可见。

关于c# - RunSpacePool如何传递共享变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38943609/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com