在Powershell中运行空间处置(特定于GUI)

时间:2018-08-11 12:44:32

标签: powershell dispose runspace

我是StackOverflow的活跃读者,因为它通常可以帮助我解决所有问题。
但是对于我的第一个问题,我将向您询问有关Powershell中运行空间的帮助,特别是用于内存管理。

我使用GUI创建了一些PS应用程序,现在我使用运行空间来避免在运行大型操作时GUI死机。 我的问题是我无法在运行空间完成后对其进行处置。

关于下面的代码,这是一个简单的脚本,用于尝试了解如何处置运行空间。我试图结合一个独特的运行空间来监视和处置应用程序运行空间,我从proxb's script(巨大的粉丝)中获得了启发,但似乎不起作用。

每次执行运行空间时,我都会获得10Mb的内存,巨大的泄漏!

leak

能帮我解决这个问题吗?

[xml]$xaml = @'
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Runspace" FontFamily="Calibri" Height="400" Width="400" FontSize="14">
    <Grid Margin="10,10,10,10">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="10"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <TextBox x:Name="TB_Results" Grid.Row="0" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto"/>
        <Button x:Name="BT_Run" Grid.Row="2" Content="Run" Height="30"/>
    </Grid>
</Window>
'@

# Inits
Add-Type -AssemblyName PresentationFramework            
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase
$gui = [hashtable]::Synchronized(@{})
$reader = (New-Object Xml.XmlNodeReader $xaml)
$gui.Window = [Windows.Markup.XamlReader]::Load($reader)
$xaml.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | ForEach-Object { $gui.Add($_.Name,$gui.Window.FindName($_.Name)) }
$Script:Jobs = [system.collections.arraylist]::Synchronized((New-Object System.Collections.ArrayList))
$Script:JobCleanup = [hashtable]::Synchronized(@{ Host = $host })

# Test function
function RunFunc {
        $newRunspace = [runspacefactory]::CreateRunspace()
        $newRunspace.ApartmentState = "STA"
        $newRunspace.ThreadOptions = "ReuseThread"
        $newRunspace.Open()
        $newRunspace.SessionStateProxy.SetVariable("gui",$gui)
        $Code = {
            $memupdate = "Memory: $($(Get-Process -Id $PID).PrivateMemorySize64 / 1mb) mb"
            $gui.Window.Dispatcher.invoke("Normal",[action]{
                $gui.TB_Results.Text = "$memupdate`r`n" + $gui.TB_Results.Text
            })
        }
        $Powershell = [powershell]::Create().AddScript($Code)
        $Powershell.Runspace = $newRunspace
        [void]$Script:Jobs.Add((
            [PSCustomObject]@{
                PowerShell = $PowerShell
                Runspace = $PowerShell.BeginInvoke()
            }
        ))
}

# Background Runspace to clean up jobs
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"          
$newRunspace.Open() 
$newRunspace.SessionStateProxy.SetVariable("jobs",$Script:Jobs) 
$Code = {
    $JobCleanup = $true
    do {    
        foreach($runspace in $jobs) {            
            if ($runspace.Runspace.isCompleted) {
                $runspace.powershell.EndInvoke($runspace.Runspace) | Out-Null
                $runspace.powershell.dispose()
                $runspace.Runspace = $null
                $runspace.powershell = $null               
            } 
        }
        $temphash = $jobs.clone()
        $temphash | Where-Object { $_.runspace -eq $Null } | ForEach-Object { $jobs.remove($_) }        
        Start-Sleep -Seconds 1     
    } while ($JobCleanup)
}
$Powershell = [powershell]::Create().AddScript($Code)
$Powershell.Runspace = $newRunspace
$PowerShell.BeginInvoke()

# gui events
$gui.BT_Run.add_Click({ RunFunc })
$gui.Window.ShowDialog() | Out-Null

1 个答案:

答案 0 :(得分:3)

调用$runspace.PowerShell.Dispose()时,PowerShell实例已被处置,但是与其绑定的运行空间并未自动处置,您需要在清理任务中首先这样做:

$runspace.powershell.EndInvoke($runspace.Runspace) | Out-Null
$runspace.powershell.Runspace.Dispose() # remember to clean up the runspace!
$runspace.powershell.dispose()