Sunday, November 16, 2008

Some Facts About Timer

There are two timers available in .Net with different type of behavior. Please consider these things when you are using the timer.
1. System.Windows.Forms.Timer :
This timer depends on windows messaging and it posts WM_TIMER message to the parent windows message queue. Windows message pump then picks it up and calls the corresponding event handler. This method is not suitable where accurate timing is required. If some other message handler not freeing the processor (thread) for a while can cause delay in calling the timer event handler. Since this is executed in main thread and message pump there is chance of a re-entrancy to the same timer routine before completing the handler. Thus we don’t need to bother about thread syncronization stuff. Another adavnatge is that it is executed in the main GUI thread context and hence we can access GUI elements with out worrying about thread sync problems (ie with out using Invoke(..))
· Not suitable for time taking calculation as it can freeze the GUI
· Not suitable for tasks those needed network operation, any error or delay in connection can cause GUI freezing
This timer routine is having a completely different behavior and system creates a thread to execute the handler. Implementation must be thread safe. If the first call to the timer routine is not finished before the timer expire will case the system to create another thread to execute the new instance of the Timer call back routine. This will definitely create a reentrancy problem. Accessing GUI elements from this timer routine must be done in a thread safe manner. (use Invoke(..))
· Good for long calculations
· Good for handling network calls
· Make sure all precautions took for a multithreaded environment.

Some points stated here especially about usage of invoke need to be tested.

No comments: