Tuesday, October 13, 2009

Timer in managed Windows Service

Writing a managed Windows service be careful trying to implement any timer functionality: Timers from Forms namespace won't work - mostly

Use System.Threading.Timer instead.
A couple things to know:
1. Use the Timer constructor wisely:
public Timer(
TimerCallback callback, // create a private void method with only stateInfo
// argument (the method signature is essential)
Object state, // can be null if you do not plan to use a sync object
int dueTime, // delay before first timer event gets fired
int period // timer event interval - what else
)
2. Use Change method to Stop/Restart the timer:
public bool Change(
int dueTime, // set Timeout.Infinite to stop the timer or smth else to continue
int period // see above
)

3. Do not forget to Dispose() the timer when it is no more required

Enjoy!

No comments: