Question

this time I come to you guys asking for help with Timers (System.Timers to be specific, I believe)

I need to make a timer that runs a function every second, so far this is what I've got:

 public class Game1 : Microsoft.Xna.Framework.Game 
 {
     Timer CooldownTracker;

     protected override void LoadContent()
     {
        CooldownTracker = new Timer();
        CooldownTracker.Interval = 1000;
        CooldownTracker.Start();
     }

     private void DecreaseCooldown(List<Brick> bricks)
     {
         foreach (Brick brick in bricks)
         {
            if (brick.Cooldown == 0)
                brick.Cooldown = 2;
            else
               brick.Cooldown--;
         }
     }
 }

...How do I make the timer run the DecreasedCooldown(List bricks) function? I've tried with Timer.Elapsed but I get nothing, I can't pass down the arguments that way. Any ideas?

Thanks!

Was it helpful?

Solution

You need to attach a Timer Elapsed event like:

CooldownTracker = new Timer();
CooldownTracker.Elapsed += CooldownTracker_Elapsed; //HERE
CooldownTracker.Interval = 1000;
CooldownTracker.Start();    

and then the event:

void CooldownTracker_Elapsed(object sender, ElapsedEventArgs e)
{
    DecreaseCooldown(yourList);
}

OTHER TIPS

You can use Thread if you want. It's not so accurate maybe cause of ThreadPool but can help. Like

private bool run = true;



Thread timer = new Thread(Run);
timer.Start();

And define Run

private void Run()
{
     while(run)
     {
         // Call function
            Thread.Sleep(1000); //Time in millis
     }
}

if you get cross-thread exception try to use for loop instead of foreach or lock your resources.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top