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?
Yes, they run in a different thread.
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.
Timer is not thread-safe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With