Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Timers.Timer() Firing multiple times due to aggregation of Elapsed Events

Tags:

c#

I want to have a section of my code start a timer once it's called, and I want this timer to keep running until I quit the whole program. My problem is, each time I call OnSomethingHappens() , the Elapsed events aggregate (despite my effort with -= ) and the timer starts firing one extra time (or at least this is what I think is happening). I have also tried defining the timer within the class, to no avail. Here's the related part of my code:

public override void OnSomethingHappens()
    {
        Timer aTimer= new System.Timers.Timer();
        aTimer.Elapsed -= (sender, e) => DoSomethingElse(sender, e);
        aTimer.Stop();
        aTimer.Close();
        aTimer.Elapsed += (sender, e) => DoSomethingElse(sender, e);
        aTimer.Interval = 1000;
        aTimer.AutoReset = true; // I want the timer to keep working, but only fire once each time
        Console.WriteLine("Enabling Timer aTimer");
        aTimer.Start();
}

I cannot use static (not sure how that would help but I saw timers being defined as static in many sources) because this class has many instances, and I want them to have separate timers.

Thank you.

like image 772
marisoy Avatar asked Dec 17 '25 01:12

marisoy


1 Answers

Start your timer without the AutoReset and restart it at the end of the DoSomethingElse.

aTimer.AutoReset = false;
aTimer.Start();

DoSomethingElse(..)
{
   // do stuff here
   aTimer.Start();
}
like image 103
Rob Smyth Avatar answered Dec 19 '25 14:12

Rob Smyth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!