Skip to content

Commit

Permalink
Work around InvalidOperationException from Console API (#3755)
Browse files Browse the repository at this point in the history
  • Loading branch information
jazzdelightsme authored Jul 27, 2023
1 parent c48f77d commit e5537d8
Showing 1 changed file with 34 additions and 2 deletions.
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

0 comments on commit e5537d8

Please sign in to comment.