Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispose timer

Tags:

c#

I have the following code which uses the System.Timers.Timer:

// an instance variable Timer inside a method
Timer aTimer = new Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
aTimer.Interval = 300000;
aTimer.AutoReset = false;
aTimer.Enabled = true;
while (aTimer.Enabled)
{
    if (count == expectedCount)
    {
        aTimer.Enabled = false;
        break;
    }
}

And I have the following code to handle the event:

private static void OnElapsedTime(Object source, ElapsedEventArgs e)
{
    // do something
}

The question is: if the timer event gets triggered and enters the OnElapsedTime, would the Timer object stops and be properly garbage collected? If not, what can I do to properly dispose of the Timer object/stop it? I don't want the timer to suddenly creep up and cause havoc in my app.

like image 405
BeraCim Avatar asked Dec 07 '22 01:12

BeraCim


1 Answers

Call Timer.Dispose: http://msdn.microsoft.com/en-us/library/zb0225y6.aspx

private static void OnElapsedTime(Object source, ElapsedEventArgs e)
{
    ((Timer)source).Dispose();
}
like image 167
Eric Mickelsen Avatar answered Dec 09 '22 14:12

Eric Mickelsen