System.Timers.Timer Vs System.Threading.Timer

I researched this topic for the benefits of my team in current software development project (Time Attendance & Door Security System) because the books and online resources are not very direct about this topic. It is impossible for a single book or resources to tell-all because there are just too much to explain.

Ok, let's begin.

Similarities
  • Both are timers (non GUI based).
  • Both will create thread process using worker thread via threadpool.
Unique Characteristics

System.timers.timer:
  • 'Start' and 'stop' method
  • Interval cannot be dynamically set while process is running
System.threading.timers:
  • No 'start' and 'stop' method
  • Cater for interval to be dynamically set at anytime

Application

So, when should you use system.timers.timer and system.threading.timers ?

System.timers.timer:
  • When you need a timer process which requires start and stop.
  • When you have a timer process which have a longer interval (i.e 30 minutes).
  • When you have a process which block (synchronous process)
System.threading.timer:
  • When you need a timer which you wanted to dynamically change the interval at any moment of the process.
  • When you need a timer which runs at a short interval (i.e 10 miliseconds)
  • When you have a process which doesn't block (asynchronous process)
  • For non GUI processes.
Precaution/Note

Since both rely on the threadpool to start the thread process, you have to make sure that thread-concurrency is properly implemented.

It is a common mistake to assume that when executing thread processes via threadpool, there is no need to perform thread-concurrency. Especially if you are using system.threading.timer.

This is because even though threadpool queues the thread processes, it is hard to control in terms of atomic timing accuracy, how the queued processes will race-condition against each other. Just take my word, implement thread-concurrency even if you are using threadpool.

MSDN relates this to the concept of 'reentrant'. Go check it out.

Download sample code (VB.NET Visual Studio 2008 SP1).In this sample, it explores implementation of both timers for the same task.

Please also refer to System.Timers.Timer Hung or Hangs

Also refer to methods for thread concurrency.

Comments