0

I have below example in my script. I call same runspace and same script block but with different arguments. The purpose is to update many windows forms in a responsive GUI.

The problem is that all finished instances are kept in the memory. If I make too many call PowerShell freeze.

Is there a way to cleanup all finished instances and keep the running ones? How can I force remove all instances before I close the script?

$sync = [Hashtable]::Synchronized(@{})

$ScriptBlock = {
    $task = [PowerShell]::Create().AddScript({
        Param($var, $var2, $var...)
        # Do some stuff... Update $sync.data in many windows forms
        # .....
        # whe finish cleanup only this particular instance
    }).AddArgument($var1,$var2)

    $runspace = [RunspaceFactory]::CreateRunspace()
    $runspace.ApartmentState = "STA"
    $runspace.ThreadOptions = "ReuseThread"
    $runspace.Open()
    $runspace.SessionStateProxy.SetVariable("sync", $sync)

    $task.Runspace = $runspace
    $task.BeginInvoke()
}

$sync.data = $value

while (<#Condition true#>) {
    Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $var1, $var2
}
Vinkelman
  • 117
  • 1
  • 7

0 Answers0