While working with a script that uses a RunSpace, I found that it takes up more and more system memory. As far as I understand, this is due to the fact that open RunSpace do not close when completed. They remain in memory, accumulating megabytes.
How to close the RunSpace, correctly? However, I do not know how long it will take - 1 second or 1 hour. Closes itself when completed.
As an example, I will give arbitrary scripts.
The first script is how I do the closing of the RunSpace as it is completed (and it apparently does not work).
$Array = 1..10000
$PowerShell = [PowerShell]::Create()
$RunSpace = [Runspacefactory]::CreateRunspace()
$RunSpace.Open()
$RunSpace.SessionStateProxy.SetVariable('Array', $Array)
$RunSpace.SessionStateProxy.SetVariable('PowerShell', $PowerShell)
$PowerShell.Runspace = $RunSpace
[void]$PowerShell.AddScript({
# Fill the system memory so that it can be seen in the Task Manager.
$Array += $Array
$Array
# Closing the Process, which should close the RunSpace, but this does not happen.
$Powershell.Runspace.Dispose()
$PowerShell.Dispose()
})
$Async = $PowerShell.BeginInvoke()
# Other jobs in the main thread...
The second script seems to be more correct, judging by the system memory. However, of course it is not applicable in life, as the Start-Sleep 10
freezes the main Process.
$Array = 1..10000
$PowerShell = [PowerShell]::Create()
$RunSpace = [Runspacefactory]::CreateRunspace()
$RunSpace.Open()
$RunSpace.SessionStateProxy.SetVariable('Array', $Array)
$PowerShell.Runspace = $RunSpace
[void]$PowerShell.AddScript({
# Fill the system memory so that it can be seen in the Task Manager.
$Array += $Array
$Array
})
$Async = $PowerShell.BeginInvoke()
Start-Sleep 10
$PowerShell.EndInvoke($Async) | Out-Null
$PowerShell.RunSpace.Dispose()
$PowerShell.Dispose()
# Other jobs in the main thread...
Please write me the correct way to close the RunSpace as it is completed. Thanks you