- Windows Service Basics
- The Timer Approach
- Comparing the Options
- Conclusion
Comparing the Options
In addition to the implementation itself, the three methods differ in a few other aspects:
- Performance. There doesn't seem to be much of a difference, even though the timer approach requires a couple of extra threads for the timer.
- Implementation (coding). The timer approach is the simplest, single-threaded is slightly more complex, and the multithreaded approach requires the most code.
- Ability to run multiple threads. This is inherently available in the multithreaded approach. The number of threads can be specified in the config file so that it's easy to increase or decrease the worker threads. You can also achieve multiple threads in the timer approach, but with additional code.
- Setting different delay periods for each thread. Inherent in the multithreaded approach. You could specify the delay for each thread in the config file and make the threads sleep for each of their specified times. The timer approach doesn't have this flexibility; the timer fires at preset intervals, so you would have to go through some hoops to achieve this goal.
- Delay in one thread could hold up execution of other threads. This won't happen in the multithreaded approach. Each thread is executing unaware of the other threads. But in the timer approach, if we spawn multiple worker threads, the longest executing thread will determine when the next execution is possible.
The following table compares the different approaches.
Feature |
Timer-based |
Single thread |
Multithreaded |
Multiple threads |
Possible with additional coding |
No |
Yes—number of threads can be varied without additional code |
Ability to set varying idle times for each thread |
No |
N/A |
Yes |
Delay in one thread can hold up next execution for all threads |
Yes |
N/A |
No—threads execute independently of each other |
Code complexity |
Lowest |
Low |
Medium |
Timer resource required |
Yes |
No |
No |
It's also possible to spawn multiple services within the same service process. Listing 13 shows the Main() method that the .NET service template generates.
Listing 13 Main method created by the .NET service template.
static void Main() { System.ServiceProcess.ServiceBase[] ServicesToRun; // More than one user service may run within the same process. To add // another service to this process, change the following line to // create a second service object. For example, // // ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()}; // ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); }
I haven't covered this option in this article because we're considering how to create background threads in a given service, rather than having multiple services running in the same process.