Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to stop System.Timers.Timer?

So I know because of the Question Can Timers get automatically garbage collected? that the System.Timers.Timer will not be garbage collected in the first place.

But my actual question is - do i have to stop or dispose the Timer?

private void CreateTimer()
{
    var timer = new Timer();
    timer.Elapsed += TimerElapsed;
    timer.Interval = 30000;
    timer.AutoReset = true;
    timer.Enabled = true;
}

I mean this Timer will run forever. But now I have no need anymore for my object that created the Timer in the Method. Do I have to stop or dispose the Timer that it gets garbage collected?

like image 798
Peter Avatar asked Sep 25 '17 12:09

Peter


People also ask

Does system timers timer run in a separate thread?

Yes, they run in a different thread.

What does the system timer do?

A system clock or system timer is a continuous pulse that helps the computer clock keep the correct time. It keeps count of the number of seconds elapsed since the epoch, and uses that data to calculate the current date and time.

Is system threading timer thread safe?

Timer is not thread-safe.


1 Answers

I don't think it will be garbage collected till you call .Dispose() on it. It does not matter whether you .Stop() the timer.

So it appears that calling Timer.Stop() or setting Timer.Enabled to false should be enough, because that would call Timer.Dispose() for you. Ref: Timer.Enabled

From MSDN:

Always call Dispose before you release your last reference to the Component. Otherwise, the resources it is using will not be freed until the garbage collector calls the Component object's Finalize method. More here

If you'd like it to be automatically disposed off, then put that logic in a separate method using the Timer.Elapsed property as explained Here.

like image 116
Faheem Avatar answered Oct 09 '22 03:10

Faheem