If you're using the timer, there is one problem: a polling time might sometimes be longer then the timer period; so what you are going to do if the polling is incomplete when another timer tick calls your callback or event handler?
Create a thread polling the database in cycle all the time. Now, you can do two things: 1) add some delay in cycle using
; 2) Throttle thread cycle execution with
from the timer event handle. Both ways do not waste CPU time when a thread is in a wait or sleep state: OS switched the thread off and never schedule it back to execution until it is waken up by the expiration time (or
I prefer the second, a little more sophisticated way. It provides better timing. When a polling time is less then the timer period, the polling happens with the period of the timer, and when this period of time is not enough for polling, the process becomes just slower as in continues polling (it cannot be faster anyway, and the polling time depends on a query, current data and other factors, including random factors); in this case all redundant timer events are just ignored.
For this purpose, you can use the class
. Your polling thread calls the method
on the instance of this class, and the timer calls
of the same instance.
After looking at the follow-up question, another suggestion: the thread, the timer and the event wait handle should be encapsulated in the thread wrapper, by several reasons I describe in my past solutions:
How to pass ref parameter to the thread
change paramters of thread (producer) after it started