2

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.

Justin Jones
  • 164
  • 6

2 Answers2

2

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.

Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
  • 2
    Even using another thread doesn't work. Aborting the thread doesn't cancel the I/O. – Gabe Dec 19 '11 at 13:38
-1

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
    }
}
Phil Lambert
  • 1,047
  • 9
  • 16
  • Thanks for the help, Phil! I thought that there would be a more simplistic solution already built-in. Your assistance is greatly appreciated. – Justin Jones Dec 19 '11 at 15:51
  • Gabe, what is the problem? Try putting a breakpoint on the DoAutomatedProcedures(); call. What it *should* be doing is allow you to input commands (which it repeats to the console) for 30 seconds. At which point it calls DoAutomatedProcedures (which does nothing). – Phil Lambert Dec 19 '11 at 18:17
  • AgentFire, how about an explanation on why Thread.Abort is completely wrong to use? – Phil Lambert Oct 24 '12 at 08:20