4

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.

5
  • 3
    while (aTimer.Enabled)... Doesn't that defeat the purpose of using a timer?
    – dtb
    Oct 8, 2010 at 4:09
  • Well I just wanted to loop while the timer is still active. The timer is really just a way for the system to wait for a certain amount of time. Threads are not favoured in my context so I opted to use timer instead.
    – BeraCim
    Oct 8, 2010 at 4:12
  • 1
    You're using a thread whether you like it or not. Thread.Sleep seems like the way to go. The code you have there is actually quite nasty performance-wise. Oct 8, 2010 at 4:14
  • @Eric Mickelsen: I'm running the above code inside Sharepoint code. I'm not too sure how SharePoint will handle threads, hence I went for Timer instead. If threads will provide better performance and neater code, I'll love to use it.
    – BeraCim
    Oct 8, 2010 at 4:24
  • 3
    My point is that your code is already executing in a thread. By using System.Timer, you're likely actually causing another thread to be used. By using System.Threading, you're not. So if your organization has some aversion to multi-threading, you are disobeying the spirit of the law in order to follow the letter of the law. Oct 8, 2010 at 4:29

2 Answers 2

14

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

private static void OnElapsedTime(Object source, ElapsedEventArgs e)
{
    ((Timer)source).Dispose();
}
1
  • 5
    The disposal is a very good practice, however the timer should be properly garbaged when it's not more running. Anyway, before invoking the Dispose method, I'd unsubscribe the event handler: that will prevent further unexpected callbacks. Aug 29, 2013 at 8:39
5

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

1
  • Unless he's enabling it again in the event handler, which is quite common. Feb 25, 2019 at 22:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.