2016-08-14 70 views
0

我想創建一個線程,將使用共享變量(主會話和線程之間),並賦予線程能力使用外部函數從主代碼RunSpacePool我如何傳遞共享變量?

我已經設法通過函數線程使用和我設法傳遞只讀變量。我的問題是,如果我正在更改線程中的變量的值,然後我嘗試從主會話中讀取它 - 我無法看到值中的更改,因此它不共享。

我該怎麼做?我的目標是最終有一條線程。

這是我的代碼:

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

任何你對任何線程的散列表都將是可訪問和可見的廣告(以及您傳遞給他人的任何數量的廣告)。