C# 暂停/恢复计时器时出现问题
我有一个迷宫游戏。按Enter键后,您可以输入作弊代码,同时计时器将暂停。但输入代码后,我的计时器会恢复,但每秒会减少3倍。以下是按Enter键的条件:C# 暂停/恢复计时器时出现问题,c#,winforms,timer,C#,Winforms,Timer,我有一个迷宫游戏。按Enter键后,您可以输入作弊代码,同时计时器将暂停。但输入代码后,我的计时器会恢复,但每秒会减少3倍。以下是按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 { p
// 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
}
下面是我的setTimer()代码:
有什么不对劲吗?我遗漏了什么吗?问题在
setTimer
方法的最后一行。计时器处理程序应该在调用构造函数后只注册一次,而不是在setTimer
中注册。在“已用计时器”事件上,处理程序将被调用,并显示其已注册的次数。因此,您使用运算符+=调用它的次数越多。每次执行以下操作时:
t、 已用+=新的ElapsedEventHandler(显示计时器);
向该事件添加一个或多个事件处理程序
这一步只运行一次,在PAR代码中,你初始化计时器< /p> HMM,我该如何解决这个问题?我真的需要不时调用该方法。我如何替换elapse timer事件?@Reinan您可以在setTimer方法开始时使用-=,取消订阅该事件,就像您使用+=。或者你可以创建计时器并从代码的其他部分订阅它,然后只在你想开始计数时启动计时器。那种“订阅”的东西对我来说是新的。必须试一试。:>成功了!非常感谢@Korneljie!:3还有@eugenehmm我应该如何解决这个问题?我确实需要不时调用该方法。尝试执行t.appeased-=new-ElapsedEventHandler(showTimer);t.经过时间之前+=新的ElapsedEventHandler(显示计时器);但如果在类构造函数中初始化事件处理程序,效果会更好。为什么pause是int而不是bool?同步代码在哪里?您使用的是没有同步的多线程。在我看来,这里不应该使用多线程。
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
}