Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I wait on console input in c# for 15 seconds or so

I need to ask for input in console and wait for few sec may be a min after that I need to default to some value. How can basically time our on console input in c# and proceed with default settings? If you have sample code that would be great.

like image 652
Prache Avatar asked Oct 17 '08 01:10

Prache


People also ask

How do you make a program wait for input?

You can wait for input in C++ by calling the cin::get() function, which extracts a single character or optionally multiple characters from the input stream. Basically, ::get() function blocks the program execution until the user provides input and specifically n character to indicate the end of the input.

What is getch () in C language?

getch() is a nonstandard function and is present in conio. h header file which is mostly used by MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it defined by POSIX. Like these functions, getch() also reads a single character from the keyboard.

How do you take input until Enter is pressed in C?

We should use "%[^\n]", which tells scanf() to take input string till user presses enter or return key. Scanf scans till user presses enter or till user presses return key.

How do you capture input in C?

In C programming, scanf() is one of the commonly used function to take input from the user.


2 Answers

You could use the timer object in System.Timers.Timer and set it to 60 secs, enable it and if someone enters something into the console just disable it, if not then just handle the what happens in the Timer.Elapsed event.

static void Main(string[] args)
        {
            System.Timers.Timer timer = new System.Timers.Timer(60000);
            timer.Elapsed += new System.Timers.ElapsedEventHandler(T_Elapsed);
            timer.Start();
            var i = Console.ReadLine();
            if (string.IsNullOrEmpty(i)) 
            {
                timer.Stop();
                Console.WriteLine("{0}", i);
            }
        }

        static void T_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Console.WriteLine("Defult Values Used");
            var T = (Timer)sender;
            T.Stop;

        }

Not sure if this is the best way. I have tested this but as I said it may not be the best way.

like image 155
Nathan W Avatar answered Oct 03 '22 23:10

Nathan W


See here, it uses a nice little polling technique on the console, which although a bit crude, very effective.

like image 20
Mark Avatar answered Oct 03 '22 22:10

Mark