我正在创建一个将执行无限进程的 C# 控制台应用程序。当用户按下转义键时,如何让应用程序“暂停”?
一旦用户按下转义键,我想要退出应用程序或从中断处继续循环的选项。我不想在这个过程中出现任何中断。如果我在第 100 步按 Esc
,我应该能够在第 101 步立即返回。
到目前为止,这是我的方法:
// Runs the infinite loop application
public static void runLoop()
{
int count = 0;
while (Console.ReadKey().Key!= ConsoleKey.Escape)
{
WriteToConsole("Doing stuff.... Loop#" + count.ToString());
for (int step = 0; step <= int.MaxValue; step++ ) {
WriteToConsole("Performing step #" + step.ToString());
if (step == int.MaxValue)
{
step = 0; // Re-set the loop counter
}
}
count++;
}
WriteToConsole("Do you want to exit? y/n");
exitApplication(ReadFromConsole());
}
有什么方法可以在单独的线程中检查用户输入键,然后在另一个线程看到 Esc
按键时暂停无限循环?
最佳答案
要找出循环中是否有可用的键,您可以这样做:
while (someLoopCondition)
{
//Do lots of work here
if (Console.KeyAvailable)
{
var consoleKey = Console.ReadKey(true); //true keeps the key from
//being displayed in the console
if (consoleKey.Key == ConsoleKey.Escape)
{
//Pause here, ask a question, whatever.
}
}
}
Console.KeyAvailable
如果输入流中有一个键可以读取并且它是一个非阻塞调用,则返回 true,因此它不会暂停以等待输入。如果条件为真,您可以检查是否按下了转义键并暂停或执行任何您想做的事情。
关于c# - 当用户按下转义键时,如何将控制台应用程序设为 "Pause"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33156267/