Skip to content
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

Work around InvalidOperationExceptions from Console API #3755

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
36 changes: 34 additions & 2 deletions PSReadLine/ConsoleLib.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,40 @@ public Encoding OutputEncoding
set { try { Console.OutputEncoding = value; } catch { } }
}

public ConsoleKeyInfo ReadKey() => _readKeyMethod.Value(true);
public bool KeyAvailable => Console.KeyAvailable;
private static T _TryIgnoreIOE<T>(Func<T> f)
{
int triesLeft = 10;
while (true)
{
try
{
triesLeft--;
return f();
}
catch (InvalidOperationException)
{
// Ignore it. An IOE could be thrown if the "application does not have a
// console or when console input has been redirected"... but we don't
// expect PSReadLine to be involved in such a situation. So we are
// actually probably running into this Issue (wherein another process
// attached to the same console terminated at just the right/wrong time):
//
// https://github.com/dotnet/runtime/issues/88697
//
// In the event there is some *other* pathological situation
// happening, we have limited the number of times we will
// swallow/retry this exception/operation.

if (triesLeft <= 0)
{
throw;
}
}
}
}

public ConsoleKeyInfo ReadKey() => _TryIgnoreIOE(() => _readKeyMethod.Value(true));
public bool KeyAvailable => _TryIgnoreIOE(() => Console.KeyAvailable);
public void SetWindowPosition(int left, int top) => Console.SetWindowPosition(left, top);
public void SetCursorPosition(int left, int top) => Console.SetCursorPosition(left, top);
public virtual void Write(string value) => Console.Write(value);
Expand Down