0

In this Link it shows how to determine if a timer is running. For me it is not working.

I have the timer declared in a static class as shown

public static class ServiceGlobals // Globals
{

    public static System.Timers.Timer _timer = new System.Timers.Timer();
}

}

On Start-up of my service, I set the timer properties

 protected override void OnStart(string[] args)
        {                  

                    ServiceGlobals._timer.AutoReset = false;
                    ServiceGlobals._timer.Interval = (3000);
                    ServiceGlobals._timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
                    ServiceGlobals._timer.Enabled = true;
                    ServiceGlobals._timer.Start(); // Start timer                  
        }

then i check if it is running in one of my methods but even when it is running the code is always false

if (ServiceGlobals._timer.Enabled) // Check if the timer is running
{
    // Return error.........

}
Community
  • 1
  • 1
user1438082
  • 2,740
  • 10
  • 48
  • 82
  • 1
    Try this and see what it returns. `ServiceGlobals._timer.Enabled = true;if (ServiceGlobals._timer.Enabled){}` – Sriram Sakthivel Apr 13 '14 at 16:25
  • 1
    Side note: 1.You shouldn't expose public fields. 2.Non public members should have "PascalCase" naming convention with no prefixes. – Sriram Sakthivel Apr 13 '14 at 16:27
  • We could already tell from your previous question that your Interval property is too short. So yes, very high odds that you'll get *false* because the Elapsed event handler is running. No guarantee however. Use a bool variable to keep track. And note the inevitable race condition, stopping the timer doesn't stop the Elapsed event handler from running nor does it prevent you from enabling the timer again. If you are sick of this class yet then [have a look here](http://stackoverflow.com/a/2033431/17034). – Hans Passant Apr 13 '14 at 18:03

1 Answers1

2

You must have missed this part of the thread you linked:

"If Timer.AutoReset is true, then Enabled will automatically be set to false the first time the timer expires."

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69