10/31/10

System.Threading.Timer

I have a data population task inside a windows service that needs to start on a certain date and repeat periodically at a specified interval. The start date and the repeat interval can be specified through a xml config file.

I decided to use the Timer class in the System.Threading namespace. It has a number of  constructor overloads and the following is the one I used :

public Timer(TimerCallback callback, Object state, TimeSpan dueTime, TimeSpan period);

where:

callback -> The method that performs the task.

It must match the signature of the System.Threading.TimerCallback delegate type that has the following signature:

delegate void TimerCallback(Object state)

state -> data that you can pass to the callback method each time it is invoked.

dueTime - > the amount of time the CLR needs to wait before calling the callback method the first time.

period -> the repeat interval

The advantage of using this Timer class is that the callback method is called by a CLR thread pool thread. The Thread Pool assigns one thread from the pool for all Timer instances. This thread keeps track of all the timers and calls them at their due time.



(reference : CLR via C# - Jeffrey Richter)

No comments: