Skip to content

How is waiting meant to work when using Runspace.OpenAsync? #7034

@alx9r

Description

@alx9r

It seems like it should be possible to subscribe to Runspace.AvailabilityChanged and Runspace.StateChanged to wait for a runspace to be opened when using Runspace.OpenAsync(). However, I have not found a way to use those events in a manner that reliably waits until the opening process is complete.

Specifically, I am surprised that the runspace transitions to Available,Opened then Busy,Opened before it completes the import of modules specified by InitialSessionState. It seems like neither the Opened nor Available states should be reached until the module is imported.

Steps to reproduce

$moduleContent = {
    function fibonacci {
        param([int]$n)
        [bigint]$a=0
        [bigint]$b=1
        foreach ($x in 0..$n)
        {
            $a,$b = $b,($a+$b)
        }
        $b
    }
    0..0 | % { fibonacci 5000 }
}

$modulePath = "$([System.IO.Path]::GetTempPath())slowLoading.psm1"
$moduleContent | Set-Content $modulePath

$initialSessionState = [initialsessionstate]::CreateDefault()
$initialSessionState.ImportPSModule($modulePath)

$runspace = [runspacefactory]::CreateRunspace($initialSessionState)
$runspace.OpenAsync()

1..500 | 
    % {
        [pscustomobject]@{
            i         = $_
            Available = $runspace.RunspaceAvailability
            State     = $runspace.RunspaceStateInfo.State
        }
        sleep 0.5
    }

Expected behavior

 i Available State
 - ---------   -----
  1      None Opening
...
  8      None Opening
  9      Busy Opening
...
285      Busy Opening
286 Available  Opened

Actual behavior

  i Available State
  - ---------   -----
  1      None Opening
...
  8      None Opening
  9 Available  Opened
 10 Available  Opened
 11      Busy  Opened
...
285      Busy  Opened
286 Available  Opened

Environment data

> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      6.1.0-preview.691
PSEdition                      Core
GitCommitId                    v6.1.0-preview.691
OS                             Microsoft Windows 6.3.9600 
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aResolution-No ActivityIssue has had no activity for 6 months or moreWG-Enginecore PowerShell engine, interpreter, and runtime

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions