I am using System.Timers.Timer class in one of the classes in my application. I know that Timer class has Dispose method inherited from the parent Component class that implements IDisposable interface. Instances of the class below are created many times during my application lifecycle; each of them has an instance of Timer class that generates Elapsed events continuously during the class’s lifecycle. Should I implement IDisposable interface in the class that uses Timer class to dispose the timer object? (I have seen code that doesn’t do this at all). I am afraid that some unmanaged resources will not be freed if I use the class below like this:
SomeClass someClass = new SomeClass(); someClass.DoSomething(); someClass = null;
The class:
using System.Timers; public class SomeClass { private Timer m_timer; public SomeClass() { m_timer = new Timer(); m_timer.Interval = 1000; m_timer.Elapsed += new ElapsedEventHandler(m_timer_Elapsed); m_timer.AutoReset = false; m_timer.Start(); } public void DoSomething() { } private void m_timer_Elapsed(object sender, ElapsedEventArgs e) { try { //Do some task } catch (Exception ex) { //Ignore } finally { if (m_timer != null) { //Restart the timer m_timer.Enabled = true; } } } }
Generally speaking you should always dispose of disposable resources. I certainly would be looking to in the case you outline above. If you implement IDisposable on the class that implements the timer you can then use the class in a using statement, meaning resources will be explicitly released when your class is disposed.