joydip_kanjilal
Contributor

How to work with Windows services in C#

how-to
Jan 08, 20164 mins
C#Microsoft .NETSmall and Medium Business

Take advantage of Windows services to build applications that you want to run in the background or execute automatically at predefined intervals of time.

A luminous clock face warps in a spiral.
Credit: Raspirator / Getty Images

A Windows service is a long-running application that can be started automatically when your system is started. You can pause your service and resume or even restart it if need be. Once you have created a Windows service, you can install it in your system using the InstallUtil.exe command line utility.

Why create a Windows service? You would typically use Windows services to implement long-running jobs that will be executed at predefined intervals of time. Your Windows service will continue to run in the background while the applications in your system can execute at the same time. Note that a Windows service can continue to execute in the background even if no one has logged into your system.

Create a Windows service project in Visual Studio

To create a Windows service in Visual Studio 2015, follow these steps:

  1. Open Visual Studio 2015 IDE
  2. Click on File -> New -> Project
  3. Select the “Windows Service” project template
  4. Specify a name for the Windows service
  5. Click OK

This will create a new Windows service project in Visual Studio.

When working with Windows services, the two main classes you will need are the service and the service installer classes. The service class is the main service file; it will typically contain all that your service is supposed to do. The service installer class contains the necessary code and metadata needed to set up your service.

Create a Windows service in C#

The source code of the default service (named Service1 and stored in the Service1.cs file) is shown below.

using System.ServiceProcess;
namespace IDGWindowsService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
        }
        protected override void OnStop()
        {
        }
    }
}

Note that all of your Windows services should extend the ServiceBase class. As you can see in the above code listing, there are two important methods in the service class: the OnStart and OnStop methods. While OnStart is fired each time your service is started by the service control manager, OnStop is fired each time the service is stopped by the service control manager.

You can then take advantage of the Timer class to specify an operation (in the OnStart() method of your service class) that you want to execute at regular intervals of time. You can specify the interval and the event handler to be called each time the interval has elapsed. And, you should disable the timer in the OnStop() method, the method that is called each time the Windows service is stopped.

Create a Windows service installer in C#

Next, double-click on the service file in the Solution Explorer window, right-click, and select “Add Installer” to create the service installer file. Now, select the service installer, right-click, and click on “Properties” to open the properties window. You can specify the service name, description, start type, modifiers, etc. for your service from the properties window of the service installer.

The two properties of importance are the service name and the start type. The service name refers to the name of the service that will be installed in your system, and the start type refers to how the service should be started. There are three possible options for the start type of the service: Automatic, Manual, and Disabled. All of these start type options should be self-explanatory.

All you now need to do is compile the solution to create the executable file for the Windows service you have implemented. Next, open the Developer Command Prompt of the version of Visual Studio that is installed in your system and then use the command line utility named InstallUtil to install the service.

If the installaton of the service is successful, you should see the following messages (among other messages) displayed in the console window, i.e., in Visual Studio Developer Command Prompt.

The Commit phase completed successfully.
The transacted install has completed.

Now, if the start type of your Windows service is set to Manual, you should start your service manually. To do this, go to Start -> Run and type “Services.msc”. When the “Services” window opens, locate your Windows service and start it manually. This is all you need to do to build and execute your Windows service.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author