Skip to content

Commit a4d4cef

Browse files
committed
Add timeout in ReadKey for event processing
The pipeline thread is blocked when PSReadline is running. When the pipeline thread is blocked, PowerShell won't process any events. I added a timeout of 300ms and check for event subscribers, if there are any, then run a bit of useless PowerShell so that the PowerShell engine will get a chance to process events. Fixes #133.
1 parent 1228790 commit a4d4cef

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

PSReadLine/ReadLine.cs

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,42 @@ private static ConsoleKeyInfo ReadKey()
108108
// First, set an event so the thread to read a key actually attempts to read a key.
109109
_singleton._readKeyWaitHandle.Set();
110110

111-
// Next, wait for one of two things - either a key is pressed on the console is exiting.
112-
int handleId = WaitHandle.WaitAny(_singleton._waitHandles);
111+
int handleId;
112+
PowerShell ps = null;
113+
114+
try
115+
{
116+
while (true)
117+
{
118+
// Next, wait for one of three things:
119+
// - a key is pressed
120+
// - the console is exiting
121+
// - 300ms - to process events if we're idle
122+
123+
handleId = WaitHandle.WaitAny(_singleton._waitHandles, 300);
124+
if (handleId != WaitHandle.WaitTimeout)
125+
break;
126+
127+
// If we timed out, check for event subscribers (which is just
128+
// a hint that there might be an event waiting to be processed.)
129+
// If there are any event subscribers, run a tiny useless bit
130+
// of PowerShell so that the events can be processed.
131+
if (Runspace.DefaultRunspace.Events.Subscribers.Count > 0)
132+
{
133+
if (ps == null)
134+
{
135+
ps = PowerShell.Create(RunspaceMode.CurrentRunspace);
136+
ps.AddCommand("Out-Null");
137+
}
138+
ps.Invoke();
139+
}
140+
}
141+
}
142+
finally
143+
{
144+
if (ps != null) { ps.Dispose(); }
145+
}
146+
113147
if (handleId == 1)
114148
{
115149
// The console is exiting - throw an exception to unwind the stack to the point

0 commit comments

Comments
 (0)