开发者

How to dispose timer

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.Enable开发者_StackOverflowd = 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.


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

private static void OnElapsedTime(Object source, ElapsedEventArgs e)
{
    ((Timer)source).Dispose();
}


You need not use while loop, AutoReset = false already make sure Timer trigger one time only.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜