Skip to content

Commit 244d97e

Browse files
Created a nested PowerShell for the top-level root (#1918)
So that events registered with the `OnIdle` engine event handler will always work.
1 parent f234a8e commit 244d97e

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

src/PowerShellEditorServices/Services/PowerShell/Host/PsesInternalHost.cs

+13-5
Original file line numberDiff line numberDiff line change
@@ -475,8 +475,18 @@ private void Run()
475475
(PowerShell pwsh, RunspaceInfo localRunspaceInfo, EngineIntrinsics engineIntrinsics) = CreateInitialPowerShellSession();
476476
_mainRunspaceEngineIntrinsics = engineIntrinsics;
477477
_localComputerName = localRunspaceInfo.SessionDetails.ComputerName;
478-
_runspaceStack.Push(new RunspaceFrame(pwsh.Runspace, localRunspaceInfo));
479-
PushPowerShellAndRunLoop(pwsh, PowerShellFrameType.Normal | PowerShellFrameType.Repl, localRunspaceInfo);
478+
479+
// NOTE: In order to support running events registered to PowerShell's OnIdle
480+
// handler, we have to have our top-level PowerShell instance be nested (otherwise
481+
// we get a PSInvalidOperationException because pipelines cannot be run
482+
// concurrently). Specifically this bug cropped up when a profile loaded code which
483+
// registered (and subsequently ran) on the OnIdle handler since it was hitting the
484+
// non-nested PowerShell instance. So now we just start with a nested instance.
485+
// While the PowerShell object is nested, as a frame type, this is our top-level
486+
// frame and therefore NOT nested in that sense.
487+
PowerShell nestedPwsh = CreateNestedPowerShell(localRunspaceInfo);
488+
_runspaceStack.Push(new RunspaceFrame(nestedPwsh.Runspace, localRunspaceInfo));
489+
PushPowerShellAndRunLoop(nestedPwsh, PowerShellFrameType.Normal | PowerShellFrameType.Repl, localRunspaceInfo);
480490
}
481491
catch (Exception e)
482492
{
@@ -964,9 +974,7 @@ private static PowerShell CreateNestedPowerShell(RunspaceInfo currentRunspace)
964974
// PowerShell.CreateNestedPowerShell() sets IsNested but not IsChild
965975
// This means it throws due to the parent pipeline not running...
966976
// So we must use the RunspaceMode.CurrentRunspace option on PowerShell.Create() instead
967-
PowerShell pwsh = PowerShell.Create(RunspaceMode.CurrentRunspace);
968-
pwsh.Runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
969-
return pwsh;
977+
return PowerShell.Create(RunspaceMode.CurrentRunspace);
970978
}
971979

972980
private static PowerShell CreatePowerShellForRunspace(Runspace runspace)

0 commit comments

Comments
 (0)