Problem while pausing / resuming timer

I have a maze game. After you press Enter, you can enter the cheat code, also the timer will stop. But after entering the code, my timer resumes, but it decreases 3 times every second. Here's the condition for pressing Enter:

// gt.setTimer() is called at the moment the maze started // I'm using getch to trap inputs else if (move == 13) //Reads if Enter is pressed { pause = 1; //A Flag saying that the timer must be paused gt.setTimer(pause); //Calls my setTimer() method Console.Write("Enter Cheat: "); cheat = Console.ReadLine(); pause = 0; //A Flag saying that the timer should resume gt.setTimer(lives, pause); //Calls again the Timer } 

Here is my setTimer () code:

 static System.Timers.Timer t = new System.Timers.Timer(); static int gTime = 300; public void setTimer(int pause) { t.Interval = 1000; // Writes the time after every 1 sec if (pause == 1) t.Stop(); // Stop the timer if you press Enter else t.Start(); // Starts the timer if not t.Elapsed += new ElapsedEventHandler(showTimer); } public static void showTimer(object source, ElapsedEventArgs e) { Console.Write("Time " + gTime); //Writes time gTime--; //Decrements the time } 

Is there something wrong? Did I miss something?

+4
source share
2 answers

Every time you do: t.Elapsed + = new ElapsedEventHandler (showTimer); you add another event handler to this event

This strind runs only once, in paired code, where you initialize the timer

+2
source

The problem is the last line of the setTimer method. The timer handler should be registered only once after calling the constructor, and not in setTimer . In an expired timer event, the handler is called the number of times it was logged. Thus, the more you use the + = operator, you call it more times.

+5
source

All Articles