You should learn how to use a
System.Timers.Timer. It will help you out in the future, it is designed to be used as a timer (quite obviously) whereas there may be some vulnerabilities if you rely on
Thread.Sleep method all of the time. You have many more options and a greater efficiency using a Timer too.
Here is an example for you.
- Code: Select all
// The millisecond interval between each time the timer ticks
public static int tick = 1000;
// The timer
public System.Timers.Timer myTimer = new System.Timers.Timer(tick);
// The time you want the timer to last for
public static int timerSeconds = 60;
// Just some method you will be using in your project as an example
public void DoStuff(string message)
{
if (message == "stop" || message == "abort")
{
myTimer.Stop();
}
else if (message == "start")
{
StartTimer();
}
}
// Assigns the tick event to the myTimer_Elapsed method
public void StartTimer()
{
myTimer.Elapsed += myTimer_Elapsed;
myTimer.Start();
}
// Called when the timer ticks (event)
private void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("Timer has ticked.");
timerSeconds--;
// If the duration has finished, stop the timer.
if (timerSeconds == 0)
{
myTimer.Stop();
}
}