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;
}
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…