Udostępnij za pośrednictwem


Using a Timer

Ok, most C# developers can probably do this in their sleep, but I needed to hook up a timer that would do something every N milliseconds. And every time, I have to decide if I need a System.Threads.Timer or a System.Timers.Timer and so on. So...

This is using the System.Threads.Timer class, since Timers had a lot of discussion about Server side coding, and I just decided that it didn't look right.

First, we need to keep the Timer in scope. I made a mistake of creating a local timer in a method, and as soon as the method ended, the Timer went out of scope and stopped working. That's not too useful. So, start with:

private Timer tickTimer;

Now, create the method that the tickTimer will call.  It has to return void and accept a single parameter as an object. So, in this case:

private void NotifyTimer(Object stateInfo)

{

      Debug.WriteLine("Tick");

}

I added the Debug statement, so I could run dbmon, and see when the timer is running. If I were 'shipping' this, I'd hide that with Debug controllers and such... but that's not a critical discussion here.

Finally, when I'm ready to start the timer, instantiate the object:

public WordGame()

{

TimerCallback notifier = new TimerCallback(this.NotifyTimer);

      this.tickTimer = new Timer(notifier, new AutoResetEvent(true), 0, 250);

}

The first line creates the method that I'm going to call whenever the timer gets called. Then, I instantiate it. I have to pass the TimerCallback as the first argument, and I have to look up what the AutoResetEvent does.

The last two arguments, in this case 0 and 250 indicate how long the timer should wait until it calls the Callback for the first time, then the interval between calls. In this case, I'm telling it to start immediately, and keep calling that callback every 250ms.

Keep in mind, in this case, that timer is going to start as SOON as my object is instantiated (note that my code is in the constructor for my class), and at the moment, it won't ever stop. I can then use Timer.Change to modify those parameters... say start the timer when the game actually starts and stop the timer once the player is out of time, but those are just some performance improvements.

Comments