开发者

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. 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's 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? Am i missing something?


The problem is in the last line of the setTimer method. The timer handler should be registered just once after calling constructor, and not in the 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.


Every time when you do: 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜