Page 3 of 5
In 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:
- You can try and handle an appropriate event that signals that there is work for the service to do. For example, you can use the FileSystemWatcher to make the service respond to a change to the filing system.
- You can implement a timer and wake the service up to do something at regular intervals.
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:
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(
timer = new System.Threading.Timer(
tick, null, 0, 10000);
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!