[英]Problem in pausing/resuming Timer
I have a maze game.我有一个迷宫游戏。 After you press Enter, you can enter a cheat code, also, the timer will pause.
回车后,您可以输入金手指码,同时计时器会暂停。 But after entering the code, my timer resumes but it decrements 3x each second.
但输入代码后,我的计时器恢复,但每秒递减 3 倍。 Here's the condition for pressing Enter:
这是按 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's my setTimer() code:这是我的 setTimer() 代码:
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?有什么不对? Am i missing something?
我错过了什么吗?
The problem is in the last line of the setTimer
method.问题出在
setTimer
方法的最后一行。 The timer handler should be registered just once after calling constructor, and not in the setTimer
.计时器处理程序应该在调用构造函数后只注册一次,而不是在
setTimer
中。 On the elapsed timer event, the handler is called the number of times it has been registered.在经过的计时器事件上,处理程序被调用它已注册的次数。 Thus the more you use operator += more times it being called.
因此,您使用 operator += 的次数越多,它被调用的次数就越多。
Every time when you do: t.Elapsed += new ElapsedEventHandler(showTimer);每次你这样做: t.Elapsed += new ElapsedEventHandler(showTimer); you add one more event handler to this event
您向此事件添加了一个事件处理程序
This strind runing only once, in par code where you initialise timer这个字符串只运行一次,在你初始化计时器的代码中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.