Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to dispose System.Timers.Timer if you use one in your application?

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;             }         }     } } 
like image 679
Roman Shumikhin Avatar asked Jan 24 '09 09:01

Roman Shumikhin


People also ask

Does system timers timer run in a separate thread?

Yes, they run in a different thread.

What is the use of system timer?

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.

Are timers thread safe?

Timer is not thread-safe.

Which of the following is a function of the timer class?

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.


1 Answers

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.

like image 108
flesh Avatar answered Oct 02 '22 06:10

flesh