From cf001fc0c366c8f4bf2b7870907a1f574dd4cd3f Mon Sep 17 00:00:00 2001 From: BDisp Date: Fri, 31 May 2024 23:08:23 +0100 Subject: [PATCH] Revert "Fixes #3520. NetDriver is consuming too much CPU resources in ReadConsoleKeyInfo." This reverts commit 79192ed8c60a6241c8f8a0a281517cade3255f97. --- Terminal.Gui/ConsoleDrivers/NetDriver.cs | 29 +++++++++++++----------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/Terminal.Gui/ConsoleDrivers/NetDriver.cs b/Terminal.Gui/ConsoleDrivers/NetDriver.cs index b6b1d6175..ee1bafe2a 100644 --- a/Terminal.Gui/ConsoleDrivers/NetDriver.cs +++ b/Terminal.Gui/ConsoleDrivers/NetDriver.cs @@ -160,7 +160,8 @@ internal class NetEvents : IDisposable public InputResult? DequeueInput () { - while (_inputReadyCancellationTokenSource is { Token.IsCancellationRequested: false }) + while (_inputReadyCancellationTokenSource != null + && !_inputReadyCancellationTokenSource.Token.IsCancellationRequested) { _waitForStart.Set (); _winChange.Set (); @@ -198,17 +199,22 @@ internal class NetEvents : IDisposable private static ConsoleKeyInfo ReadConsoleKeyInfo (CancellationToken cancellationToken, bool intercept = true) { - // The Console.KeyAvailable must only be used if - // the console is reading an Ansi escape sequence - // Task.Delay must only be used on limited situations - // and not for the entire application execution, which - // case need to use async Task to really awaiting, - // like the CheckWindowSizeChange is using - try + // if there is a key available, return it without waiting + // (or dispatching work to the thread queue) + if (Console.KeyAvailable) { return Console.ReadKey (intercept); } - catch (InvalidOperationException) { } + + while (!cancellationToken.IsCancellationRequested) + { + Task.Delay (100); + + if (Console.KeyAvailable) + { + return Console.ReadKey (intercept); + } + } cancellationToken.ThrowIfCancellationRequested (); @@ -304,10 +310,7 @@ internal class NetEvents : IDisposable break; } - if (consoleKeyInfo != default (ConsoleKeyInfo)) - { - ProcessMapConsoleKeyInfo (consoleKeyInfo); - } + ProcessMapConsoleKeyInfo (consoleKeyInfo); break; }