Joh*_*ust 7 c# multithreading console-application infinite-loop
我正在创建一个将执行无限过程的C#控制台应用程序.当用户按下转义键时,如何让应用程序"暂停"?
一旦用户按下转义键,我想要选择退出应用程序或继续循环它停止的位置.我不希望在这个过程中出现任何不连续性.如果我Esc在步骤100 按下,我应该能够在步骤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());
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在单独的线程中检查用户输入密钥,然后在另一个线程看到Esc按键时暂停无限循环?
Ron*_*yer 11
要确定循环中是否有可用的键,您可以执行以下操作:
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.
}
}
}
Run Code Online (Sandbox Code Playgroud)
Console.KeyAvailable如果输入流中的某个键已准备好读取并且它是非阻塞调用,则返回true,因此它不会暂停以等待输入.如果条件为真,您可以检查是否按下了转义键并暂停或执行任何操作.