2016-08-14 34 views
0

共有変数(メインセッションとスレッドの間)を使用するスレッドを作成しようとしています。また、メインコードの外部機能を使用するスレッドの能力を与えます。RunSpacePoolどのように共有変数を渡すのですか?

私は、スレッドを使用すると私は読み取り専用の変数を渡すために管理している。私の問題は、私はスレッド内の変数の値を変更しているし、私はメインセッションからそれを読み取ろうとしている - 私は値の変更を見ることができないので、共有されていません。

どうすればよいですか?私の目標は、最後に1つのスレッドを持つことです。

これは私のコードです:

$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 

答えて

1

同期ハッシュテーブルには何が必要でしょう。

# 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() 

いずれかのスレッドからハッシュテーブルに行う操作は、アクセス可能であり、両方のスレッド広告(およびあなたにそれを渡す他の何人かの数)。

関連する問題