Creating a .NET Windows Service: Three Different Approaches
- Windows Service Basics
- The Timer Approach
- Comparing the Options
- Conclusion
For more information on .NET, visit our .NET Reference Guide or sign up for our .NET Newsletter.
The article details three different approaches to creating a .NET service. Most common is the timer-based service, which simply relies on a timer to invoke the background thread periodically. I also cover two other alternatives: using a single worker thread and using multiple worker threads. While the timer strategy is the simplest, the approaches using a single worker thread and multiple worker threads (specifically the multithreaded approach) offer some advantages.
Windows Service Basics
Writing a .NET service is very simple. You simply create a project using the Windows Service template. Then you initialize your service in the OnStart event and tear it up in the OnStop event. But the simplicity comes at a cost: The service doesn't provide any mechanism to invoke your worker function(s) periodically. So unless you want to execute some task just once when the service starts, the template code is not very useful. Listing 1 shows the OnStart and OnStop event stubs added by the template.
Listing 1 OnStart and OnStop stubs created by the .NET service project template.
protected override void OnStart(string[] args) { // TODO: Add code here to start your service. } protected override void OnStop() { // TODO: Add code here to perform any tear-down necessary to stop your service. }