Click here to Skip to main content
12,753,195 members (36,513 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


12 bookmarked
Posted 10 Jun 2012

Easy to learn Window Service

, 13 Jun 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Here we will talk about Windows NT services, which enable you to create a long-running executable application that runs in a separate Windows session.


A Microsoft Windows service, formerly known as an NT service, enables you to create a long-running executable application that runs in a separate Windows session or we can configure the service to run in a user context other than a logged on user. 

Generally some tasks are required to be scheduled or dependent on time. They can be performed easily using a Windows service.

Benefits of a Window Service 

  • It can be run automatically. 
  • It would not require user interaction.
  • It runs in the background.
  • Services can be automatically started when the computer is booted.
  • We have one place to look at to manage/reconfigure/monitor all of our services.

Steps to create a Windows service

  1. Create a Windows Service Project using Visual Studio
  2. Create an Installer
  3. Deploy the Service
  4. Verify that the service works
  5. Un-install the service   

Creating a Windows Service Project Using Visual Studio 

  1. Open Visual Studio -> File -> New Project-> Visual C# -> Windows -> select Windows Service project and give it a meaningful name.
  2. Switch to code view, to start developing (Right Click -> View code).
  3. Let's start writing the code. Most services have timers implemented in them to perform a particular task at regular intervals in the background.
  4. Here is the sample code. If the available amount of RAM exceeds 500 MB then a message is written in the log file on a specified interval.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO; 
namespace serverMonitor
    partial class Service1 : ServiceBase
        privateTimer timer1 = null;
        public Service1()
        protected override void OnStart(string[] args)
            timer1 = newTimer();
            this.timer1.Interval = 30000;
            this.timer1.Elapsed += newSystem.Timers.ElapsedEventHandler(this.timer1_Tick);
            timer1.Enabled = true;
            Log("Service Started successfully"); 
        protected override void OnStop()
            timer1.Enabled = false;
            Log("Service Stopped successfully");         
        private void timer1_Tick(object sender, EventArgs e)
        public static void ServerMonitor()
                PerformanceCounter ramCounter;
                ramCounter = new PerformanceCounter("Memory", "Available MBytes"); 
                if(ramCounter.NextValue() > 500)
                Log("Amount of the available RAM :" + ramCounter.NextValue() + "Mb");             
            catch (Exception ex)
                Log("Error =" + ex.ToString());
        public static void Log(string str)
            StreamWriter fileWritter = File.AppendText(@"d:\Log.txt");
            fileWritter.WriteLine(DateTime.Now.ToString() + " " + str);

Creating an Installer

  1. Now after the code is written successfully, it's time to install the service. For this you need to add the service installer to the project.
  2. Right-click any were in the Service1.cs file and select 'Add Installer'. Once we select, 'Add Installer', the Visual Studio IDE will automatically create "ProjectInstaller.cs" of this service.
  3. Build this project. It will create an exe of this project. 

Deploying Service 

  1. Open the Visual Studio Command prompt from "Start ->All Programs->Microsoft Visual Studio 2010 ->Visual Studio Tools -> Visual Studio Command Prompt (2010)".
  2. Navigate to the folder where our 'Windows Service' application is compiled.
  3. Type 'Installutil<<Service Name>>.exe as given below:
  4. C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe "Service1.exe"

Note: If we select the 'Account' type as 'User', the application will prompt for username and password in which the context service needs to run. 

Verifying whether service works  

  1. Once the service is installed successfully, you can see your service by going to Start -> Run ->"Services.msc"; you will see your service. You can test this service. Right-click on My Computer -> Computer Management ->Services->Select Service and Right Click -> Start.
  2. Then you will see the log file in 'd:\Log.txt" as we implemented in the service. It will generate a log every 30 seconds.

Un-Installing the service

Type 'Installutil /u <<Service Name>>.exe as given below:

C:\WINDOWS\Microsoft.NET\Framework\ v4.0.30319\InstallUtil.exe /u "Service1.exe"

Points of Interest   

It's very easy to learn how to write a Windows service but difficult to track errors.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

purnananda behera
Software Developer (Senior)
India India
I am a professional programmer with 5+ years of experience. Having a strong grasp over C# .NET/ASP.NET/MVC/WCF/WPF/MS SQL/ORACLE/BOOTSTRAP etc. I am equally efficient with Web based as well as Windows projects.

You may also be interested in...


Comments and Discussions

Questionhow can i update my windows service? Pin
haifa20105-May-15 1:43
memberhaifa20105-May-15 1:43 
GeneralMy vote of 5 Pin
purnananda behera6-May-13 1:59
memberpurnananda behera6-May-13 1:59 
GeneralMy vote of 1 Pin
Jalapeno Bob15-Jun-12 11:12
memberJalapeno Bob15-Jun-12 11:12 
GeneralRe: My vote of 1 Pin
Kees van Spelde19-Nov-14 7:30
professionalKees van Spelde19-Nov-14 7:30 
GeneralMy vote of 1 Pin
maq_rohit13-Jun-12 16:49
membermaq_rohit13-Jun-12 16:49 
Questionthanks for your share Pin
aaaanhnung13-Jun-12 10:39
memberaaaanhnung13-Jun-12 10:39 
GeneralMy vote of 2 Pin
Vitaly Tomilov13-Jun-12 2:19
memberVitaly Tomilov13-Jun-12 2:19 
GeneralMy vote of 1 Pin
Klaus Luedenscheidt12-Jun-12 18:51
memberKlaus Luedenscheidt12-Jun-12 18:51 
GeneralMy vote of 1 Pin
Forogar12-Jun-12 4:15
memberForogar12-Jun-12 4:15 
GeneralRe: My vote of 1 Pin
purnananda behera12-Jun-12 21:09
memberpurnananda behera12-Jun-12 21:09 
GeneralMy vote of 1 Pin
Dave Kreskowiak12-Jun-12 3:11
mvpDave Kreskowiak12-Jun-12 3:11 
QuestionHow the ....??? Pin
Dave Kreskowiak12-Jun-12 3:11
mvpDave Kreskowiak12-Jun-12 3:11 
AnswerRe: How the ....??? Pin
Manas Bhardwaj12-Jun-12 23:05
memberManas Bhardwaj12-Jun-12 23:05 
GeneralRe: How the ....??? Pin
Jani Giannoudis13-Jun-12 2:11
mvpJani Giannoudis13-Jun-12 2:11 
QuestionHow is this used in a perfect world?! Pin
VallarasuS12-Jun-12 1:18
memberVallarasuS12-Jun-12 1:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170217.1 | Last Updated 13 Jun 2012
Article Copyright 2012 by purnananda behera
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid