Justin Jones
Justin Jones

Reputation: 164

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.

Upvotes: 2

Views: 894

Answers (2)

Phil Lambert
Phil Lambert

Reputation: 1047

That was quite a tough one! However I'm bored and like a challenge :D Try this out...

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
    }
}

Upvotes: -1

Eugen Rieck
Eugen Rieck

Reputation: 65274

This is suprisingly difficult: You have to start a new thread, do the ReadLine on this new thread, on the main thread wait with timeout for the new thread to finish, if not abort it.

Upvotes: 2

Related Questions