On Sun, 01 Apr 2007 23:20:29 -0700, SriBhargav <sr************@gmail.com>
wrote:
[...]
I would like the user to input something through Console.readline() in
5 secs. If there is no input in that time, I would like to proceed
further with the program logic.
I had a difficulty in implementing this, as console.readline()
indefinitely waits for the user input.
Can somebody help me to implement this in c#?
I've got to say, your question provided me with the opportunity for a
little chuckle. Not because of your post per se, but I decided to browse
the docs a little in the Console class and I found a pretty funny pair of
document pages:
http://msdn2.microsoft.com/en-us/lib....readline.aspx http://msdn2.microsoft.com/en-us/lib...sole.read.aspx
In the former (the docs for Console.ReadLine), they recommend using
Console.Read so as to "produce robust code". In the latter (the docs for
Console.Read), they claim that Console.ReadLine is preferable to using
Console.Read. It's like the two methods were documented by different
writers, and neither really wants "their" method to be used.
I hope no one at Microsoft wonders why it is people sometimes get confused
trying to figure out .NET. :)
Anyway, as far as the actual question goes, it seems to me that there are
at least a few possibilities:
* Use Console.KeyAvailable and Console.ReadKey together to check for
input. Since you'd have to poll the Console in order to avoid making the
user wait too long when they DO provide input, this seems to me the least
desirable solution. However, in a console application where you're
waiting for input and aren't doing anything else anyway, I don't suppose
it would hurt anything to just check for user input every quarter second
or so (obviously you don't want to just poll without any sort of delay
between checks, and I think a quarter second would probably be sufficient
to allow your application to appear to be responsive).
* Get the input stream for Console and then set the ReadTimeout
property of that stream. Note that I don't actually know for sure that
the default input stream for Console actually supports the ReadTimeout
property. You'll have to check that yourself. But if it does, perhaps
that would do what you want.
* Read the input on a separate thread (using Read or ReadLine) and
maintain a timer that aborts the thread if no user input has been provided
by a certain time. Yes, it involves aborting the thread and personally I
don't like doing that. However, as far as I know there's no mechanism to
cause the Console input method to be interrupted, and so the only option
appears to me to be to just stop the thread that's blocked on the Console
input method.
If it were me, I would investigate whether the ReadTimeout property is
supported for the Console input stream and use that if it is. If it's
not, I'd probably go with the first method (polling), even though I don't
like polling very much. I like aborting threads even less than I like
polling. :)
Pete