简体   繁体   English

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

[英]How to have a c# console application wait (synchronously) for user input (ReadKey/ReadLine) for a duration?

I have a console application that runs automated procedures on a server. 我有一个控制台应用程序,可在服务器上运行自动化程序。 However, there are routines that may require user input. 但是,有些例程可能需要用户输入。 Is there a way to have the console wait for user input for a set amount of time? 有没有一种方法可以让控制台在设置的时间内等待用户输入? If there is no user input, proceed with execution, but if there is input, then process accordingly. 如果没有用户输入,则继续执行,但是如果有输入,则进行相应处理。

这非常困难:您必须启动一个新线程,对该新线程,主线程上的ReadLine进行等待,等待超时,直到新线程完成(如果不中止)。

That was quite a tough one! 那是相当艰难的! However I'm bored and like a challenge :D Try this out... 但是我很无聊,喜欢挑战: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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM