Console.ReadLine Break

孤街醉人 提交于 2019-12-12 15:14:41

问题


I'm trying to figure out how I can use Console.ReadLine and a timer. My console program is designed to run a long process automatically, with this process restarting every 30 seconds after the previous process completed. I want to give the user the ability to break the auto-run by typing a command though. If I use Console.ReadLine() though, it will wait until the user enters something, whereas I want the program to continue on through a loop if nothing is entered within 30 seconds. . . Any thoughts??

For example:

RunProcess > Wait 30s for User Input. If none: Continue Loop

Thanks a lot!


回答1:


You could run your timer on a separate thread. When the user enters text, store it in a variable that is accessible to both threads. When the timer ticks, see if anything is entered and continue accordingly.

Be sure to be thread safe :-)

EDIT:

You can use a System.Threading.Timer to tick every 30 seconds and in its callback method, check if the text has been set.




回答2:


Don't use Console.ReadLine() but check if Console.KeyAvailable is true and then read Console.ReadKey() to check for exit condition.

Try this example code

class Program
{
    static bool done;
    static void Main(string[] args)
    {
        int count = 0;            
        done = false;
        while (!done)
        {
            Thread.Sleep(2000);
            count++;
            Console.WriteLine("Calculation #" + count.ToString());
            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo key = Console.ReadKey();
                if (key.Key == ConsoleKey.Escape)
                {
                    done = true;
                }
            }                                
        }
        Console.WriteLine();
        Console.WriteLine("end");
    }
}


来源:https://stackoverflow.com/questions/4821290/console-readline-break

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!