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; } } } }
Yes, they run in a different thread.
The System. Timers. Timer class has the same resolution as the system clock. This means that the Elapsed event will fire at an interval defined by the resolution of the system clock if the Interval property is less than the resolution of the system clock.
Timer is not thread-safe.
Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With