Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, October 21, 2014 3:46 AM
To make the program more nice i thought to add a timer in which it will ask from to "press any key to continue within 5 sec" if user enter any key then program returns else it exit
so i wrote this simple code for testing but its not working..so please help me to complete the task
using System;
using System.Threading;
namespace Timer
{
class Program
{
static void Main(string[] args)
{
for( ; ; )
{
Console.WriteLine("Hello World.. :)");
for (int i = 5; i >= 0;i-- )
{
Thread.Sleep(1000);
Console.Write("\rPress any key to continue within {0} seconds..",i);
if (i == 0)
System.Environment.Exit(1);
else if(i!=0)
continue;
}
}
}
}
All replies (4)
Tuesday, October 21, 2014 5:07 AM âś…Answered | 1 vote
I shouldn't really write the code for you, but I'm a sucker for being called 'Sir'.
The link that I gave you before was for System.Threading.Timer, but I now think that System.Timers.Timer is better for this purpose because it's easier to reliably stop. Put System.Timers.Timer into Google to find out more.
Here's the code.
using System;
using System.IO;
using System.Timers;
namespace Timer
{
class Program
{
static void Main(string[] args)
{
Timer timer = new Timer(5000);
timer.Elapsed += TimerTick;
timer.Start();
Console.WriteLine("Press a key to continue.");
Console.ReadKey();
timer.Stop();
Console.WriteLine("Stopped");
Console.Read();
}
static void TimerTick(Object obj, ElapsedEventArgs e)
{
Console.WriteLine("Exiting");
Environment.Exit(0);
}
}
}
Tuesday, October 21, 2014 4:02 AM | 1 vote
Greetings Palash.
Generally, if you think that you have found a use for Thread.Sleep, it's a good idea to think again.
In this case, Thread.Sleep is definitely not the right tool for the job. You need to use a Timer.
http://msdn.microsoft.com/en-us/library/system.threading.timer%28v=vs.110%29.aspx
Set the Timer's interval to 5 seconds (5000 milliseconds). Then do a Console.Read. If the Read executes (the user has pressed a key), then stop the timer. If the Timer ticks (so the code goes into the tick event handler), then exit the program.
Tuesday, October 21, 2014 4:29 AM
thank u sir for the reply and telling me about timer class..but i can't understand it..please tell or edit the code in example sir..thanks :)
Tuesday, October 21, 2014 5:32 AM
task completed..thank u sir..thanks a lot :)