Do I have to stop System.Timers.Timer?

Viewed 5010

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?

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.

Related