Skip to content

Respect cancellation in ReadOneOrMoreKeys() #3274

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 19, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions PSReadLine/ReadLine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ bool IPSConsoleReadLineMockableMethods.RunspaceIsRemote(Runspace runspace)
return runspace?.ConnectionInfo != null;
}

private void ReadOneOrMoreKeys()
private void ReadOneOrMoreKeys(CancellationToken cancellationToken)
{
_readkeyStopwatch.Restart();
while (_console.KeyAvailable)
Expand Down Expand Up @@ -144,6 +144,14 @@ private void ReadOneOrMoreKeys()
while (_charMap.KeyAvailable)
{
var key = PSKeyInfo.FromConsoleKeyInfo(_charMap.ReadKey());
if (cancellationToken.IsCancellationRequested)
{
// If PSReadLine is running under a host that can cancel it, the
// cancellation will come at a time when ReadKey is stuck waiting for input.
// The next key press will be used to force it to return, and so we want to
// discard this key since we were already canceled.
continue;
}
_lastNKeys.Enqueue(key);
_queuedKeys.Enqueue(key);
}
Expand All @@ -160,7 +168,7 @@ private void ReadKeyThreadProc()
break;

var localCancellationToken = _singleton._cancelReadCancellationToken;
ReadOneOrMoreKeys();
ReadOneOrMoreKeys(localCancellationToken);
if (localCancellationToken.IsCancellationRequested)
{
continue;
Expand Down