How to know if a System.Timers.Timer is running?

Asked

Viewed 489 times

-1

I need to know if a timer is running, in case you’re not, I’ll start it,

  • public void startTemporizador() { var timer = new System.Timers.Timer(); timer = new System.Timers.Timer { Enabled = true, Interval = 10000, Autoreset = true }; timer. Elapsed += (Sender, z) => Onteste(", ""); timer.Start(); ; }

  • when calling this method, I need to know if timer is started.

  • if I call it more than once, I will start the timer 2 times, I need to start it only once.

  • Did the posted answer solve your problem? Do you think you can accept it? If you don’t know how to do it, check out [tour]. This would help a lot to indicate that the solution presented was useful to you and to give an indication that it is satisfactory. You can also vote on any and all questions or answers you find useful on the entire site (when you have 15 points). Accepting and voting are separate things.

1 answer

2

The class Timer has nothing to control this. If you want to prevent a timer specific be created again need to create a proper control with a flag indicating that it has been started and not let start again.

Actually the problem seems different. That timer can be destroyed when the Runtime want. It is being declared locally in the method, when the method ends, the object is free to be destroyed by Garbage Collector at some point, so doing it this way is a mistake.

If the intention was that it should be destroyed then I would need to ensure that this takes place immediately with a using, I don’t think that’s the case.

If the intention is to keep the timer alive after the method is finished, and it seems to be this, it should be placed in a class instance variable to last the entire existence of the form, or even in a class static variable if the goal is to keep alive in every application. If you are raised within the class then you must take care to destroy the timer when the object containing it is destroyed (the class will need to be Disposable and it will have to be created properly for this.

You have to wonder if this is the right mechanism for what you want, I’ve seen a lot of misuse of it. If it is, you need to understand all the implications of its use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.