如何让c#控制台应用程序(同步)等待用户输入(ReadKey/ReadLine)一段时间



我有一个控制台应用程序,它在服务器上运行自动化过程。然而,有些例程可能需要用户输入。是否有一种方法可以让控制台等待用户输入一段时间?如果没有用户输入,则继续执行,但如果有输入,则相应地进行处理。

这是非常困难的:您必须启动一个新线程,在这个新线程上执行ReadLine,在主线程上等待新线程超时完成,如果不中止它

这是一个相当困难的问题!但是我很无聊,喜欢挑战:D试试这个…

class Program
{
    private static DateTime userInputTimeout;
    static void Main(string[] args)
    {
        userInputTimeout = DateTime.Now.AddSeconds(30); // users have 30 seconds before automated procedures begin
        Thread userInputThread = new Thread(new ThreadStart(DoUserInput));
        userInputThread.Start();
        while (DateTime.Now < userInputTimeout)
            Thread.Sleep(500);
        userInputThread.Abort();
        userInputThread.Join();
        DoAutomatedProcedures();
    }
    private static void DoUserInput()
    {
        try
        {
            Console.WriteLine("User input ends at " + userInputTimeout.ToString());
            Console.WriteLine("Type a command and press return to execute");
            string command = string.Empty;
            while ((command = Console.ReadLine()) != string.Empty)
                ProcessUserCommand(command);
            Console.WriteLine("User input ended");
        }
        catch (ThreadAbortException)
        {
        }
    }
    private static void ProcessUserCommand(string command)
    {
        Console.WriteLine(string.Format("Executing command '{0}'",  command));
    }
    private static void DoAutomatedProcedures()
    {
        Console.WriteLine("Starting automated procedures");
        //TODO: enter automated code in here
    }
}

最新更新