暂停/恢复计时器时出现问题

4

我有一个迷宫游戏。在按下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
            {
                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()代码:

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
    }

有什么问题吗?我漏掉了什么吗?


为什么暂停是 int 类型,而不是 bool 类型? - CodesInChaos
你的同步代码在哪里?你正在使用多线程而没有同步。我认为你不应该在这里使用多线程。 - CodesInChaos
2个回答

5
问题出在setTimer方法的最后一行。定时器处理程序应该在调用构造函数后仅注册一次,而不是在setTimer中。在经过计时器事件时,处理程序被调用了它被注册的次数。因此,您使用操作符+=的次数越多,它被调用的次数也就越多。

嗯,我该如何解决这个问题?我真的需要不时调用这个方法。 - Reinan Contawi
我该如何替换经过计时器事件? - Reinan Contawi
1
@Reinan,你可以在setTimer方法的开头使用-=取消订阅事件,就像使用+=订阅一样。或者你可以在代码的其他部分创建计时器并订阅它,然后只有在想要开始计数时才启动计时器。 - Kornelije Petak
“subscribe” 这个东西对我来说是新的。一定要试试看。:> - Reinan Contawi

2
每次执行以下代码: t.Elapsed += new ElapsedEventHandler(showTimer); 你都会向该事件添加一个新的事件处理程序。
这个字符串只运行一次,在你初始化计时器的并行代码中。

嗯,我该怎么解决这个问题呢?我真的需要不时地调用这个方法。 - Reinan Contawi
1
在执行 t.Elapsed += new ElapsedEventHandler(showTimer); 之前尝试执行 t.Elapsed -= new ElapsedEventHandler(showTimer); - Alexander Molodih
最好在类构造函数的某个地方初始化事件处理程序。 - Alexander Molodih

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接