My Colleagues Guru and Amit brought an interesting discussion on the use of timers in a multithreaded environment. I have tried below to clarify a few things about different timer classes and their usage scenarios with pros and cons. This info is based on the various blogs I have studied on multi-threading, my few practical on threads as well as teachings from Jeffrey Richter multithreading class which I just happened to attend a few days back.
A Timer is used to generate recurring events in an application. for e.g., a timer can be used to create a digi-clock in our application or to generate sample reports periodically say after every 8 hours and mail them to the stakeholders. Again, a timer can be used as a periodic polling mechanism in windows service application for queued requests. .NET framework provides multiple versions of Timer class in different namespaces with each being recommended to be used in typical fashion in specific scenarios. This article describes different containers of Timer class and how they can be best leveraged in our development scenarios.
System.Timers.Timer – for server based timer functionality, use this one as it raises events and has additional features like generating recurring events in an application, start stop methods, auto-reset flag, elapsed event etc. This timer is not visible at run time. This Server based timer is designed for use with worker threads in multithreaded environment but again, this timer is prone to race condition because server timers can move among the threads to raise the elapsed event which leads to more accuracy but prone to race. For e.g., the event handling method might run on one thread but at the same time, another thread calls the stop method. This might result in the elapsed event being raised after the timer is actually stopped.
System.Threading.Timer – this is a light weight, simple timer which uses callback methods. This timer is served by ThreadPool threads. it is not advisable to use this timer with your Windows forms or other desktop based UIs because its callbacks do not occur on the main user interface thread. The callback methods executed by the timer should be re-entrant as it is served by ThreadPool threads.
System.Windows.Forms.Timer – specifically designed for use with the GUI components e.g. in Windows Forms. This timer is optimized for use in Win Forms in the sense that it is designed for a single threaded model where UI threads are used to perform processing. Basic requirement for this is to have UI message pump available all the time and always operate from the same thread, or marshal the call to other thread. Please note that this timer is single threaded and has a limited accuracy of 55 milliseconds. If the situation demands usage of a multithreaded timer with greater accuracy, use System.Timers.Timer class instead. This timer does not use the ThreadPool obviously.