Azure-Functions icon indicating copy to clipboard operation
Azure-Functions copied to clipboard

Write-Host behaviour when using runspaces

Open spaelling opened this issue 5 years ago • 1 comments

At first I thought that there was a bug preventing the use of runspaces, but it seems that when invoking a runspace Write-Host just stops producing any output.

I have made below http trigger that creates and invokes 10 runspaces. After the first is invoked Write-Host stops "working"

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# setup runspace
Write-Host "Setting up runspace"
$sessionstate = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
            
$runspacepool = [runspacefactory]::CreateRunspacePool(1, [int]$env:NUMBER_OF_PROCESSORS+1, $sessionstate, $Host)
$runspacepool.Open()

$runspaces = [System.Collections.ArrayList]::new()        
for ($i = 0; $i -lt 10; $i++) {
    Write-Host "Creating runspace..."
    $runspace = [powershell]::Create()
    $runspace.RunspacePool = $runspacepool 
    $null = $runspace.AddScript({
        Start-Sleep -Milliseconds 750
    })
    Write-Host "Invoking runspace"
    $runspaces.Add([PSCustomObject]@{ Pipe = $runspace; Status = $runspace.BeginInvoke() })
    # after this Write-Host does not produce any output
    Write-Host "Runespace invoked"   
}

Write-Host "Waiting for runspaces to complete"
while($runspaces.Status.IsCompleted -contains $false){Start-Sleep -Milliseconds 25}
Write-Host "Runspaces completed"

$RunspacesCompleted = ($runspaces.Status | Where-Object {$_.IsCompleted}).Count

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = "Test completed $RunspacesCompleted runspaces"
})

The function does return Test completed 10 runspaces so everything seems to complete running.

This is by no means a critical error, but I would expect others using runspaces to become fairly confused as I did. It also makes it much more complicated to follow along what is happening in the code.

spaelling avatar Sep 09 '19 05:09 spaelling