c# - 当用户按下转义键时,如何将控制台应用程序设为 "Pause"?

标签 c# multithreading console-application infinite-loop

我正在创建一个将执行无限进程的 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/

相关文章:

android - 在android中检测互联网连接

java - 如何在Java中共享对象列表以进行并行处理?

c# - 如何在 C# 中隐藏控制台应用程序

c# - Xamarin 表单(Android): OnCreate bundle is null

c# - 替换方法的主体会删除以下换行符

c - Windows 线程 - 调试工作版本没有 - 尝试在线程启动时从线程获取值

c# - 无法在自定义配置文件提供程序中加载类型

c# - 在 C# 中的字符串中查找指定字符串的所有索引

c# - 使用 BitmapSource、PngBitmapEncoder/Decoder 时,在 PNG 中保存 8 位索引数据会改变原始字节

c# - 从 Programm 类开始打开一个窗口?