Windows Services implementation in C# and .NET Framework

There are times when we need to run code without user interaction. For instance, we need to listen for certain event on the network and etc… in this case regular ASP.NET development will not work and you need to use Windows Services which is the most suitable in cases like that.

Windows is exe application that has to be installed on the server and cannot be debugged in the same was as traditional application. You will have to attach debugging process to the service. Error handling is also done in a different way. We need to log error messages into Event Log versus instead of raising error messages to the interface. All the pop-ups are not visible and may actually stall the application. Windows Services run their own security context and are running without need to login to the station. As a rule of thumb, we need to be extra careful when assigning rights to user account that will be running our Windows Services. If Windows Services compromised this user account will be used to attack servers and potentially install harmful software. The best user account to set up for running Windows Service is LocalService since it has least privileges and passes this identity to other services.

Windows Services has two main methods OnStart and OnStop which house all the logic that you need Services for. If you need to check for certain events via Services you will use System.Timers.Timer component. Additional methods that come handy are OnPause, OnContinue and OnShutdown.

Windows Services installation is not as straight forward as installation of executable and you need two helper classes for this purpose: ServiceInstaller and ServiceProcessInstaller. There are several important properties such as StartType which can be Automatic, Manual and Disabled. Account property specifies security context such as LocalService, NetworkService, LocalSystem, User.

In order to install Windows services you may use utility called InstallUtil.exe with the following command: InstallUtil /u yourservice.exe or you can create setup project that will do it interactively.

If you need to control Windows Services from an Assembly you will be using System.ServiceProcess.ServiceController class.
// Connect to the Server
ServiceController myServiceController = new ServiceController("Server");
myServiceController.Stop();// Stop
// Wait two seconds
Thread.Sleep(2000);
myServiceController.Start();// Start

In order to run Overloaded Windows Service we need to use base class run() method. For instance run(ourService).

If we want to overload Service we need to reference ServiceBase class.