A Windows Service without a template |
Written by Harry Fairhead | ||||||
Friday, 14 August 2009 | ||||||
Page 3 of 5
Using timersIn most cases a service creates an object or method that does the desired task when it is started and similarly destroys that object when stopped. The big problem in building any service is to get the object to do something when action is needed. There are two general approaches:
or
The timer approach is so common that it is worth seeing how it is implemented and the final example shows how to work with an event. First we need a timer object; add: using System.Threading; to the start of the program. Unfortunately there are two timer classes, one in Windows.Forms and one in Threading. To make it clear which we want to use we need to use a fully qualified name when we declare a variable: private System.Threading.Timer timer; Now we can create the timer object and set it ticking when the service is started: protected override void OnStart( and remember to destroy the timer object when the service is stopped: protected override void OnStop() The only missing piece is the method used to create the TimerCallback delegate and this simply makes use of the message box call described earlier:
private void SayHello(object state) If you start the service a message box will pop up every 10 seconds until you stop the service. Stop the service to stop the messages! <ASIN:1861007728> <ASIN:0735625301> |
||||||
Last Updated ( Friday, 14 August 2009 ) |