Skip to main content

How to Create Windows Service C#

Language


In this tutorial we are going to learn how to create windows service. One of the powerful feature of .NET environment is it is facilitate to create windows services. Windows services are executable applications that run in background. They are controlled by Service Control Manager. According to Microsoft windows service is very much close to unix concept of cron job.
Usually starts when windows starts that’s mean windows service usually start with operating system boot up and run until operating system shut down.

Creating a service


using System;
using System.ServiceProcess;
System.Configuration.Install.Installer;

public class MyService: ServiceBase
{
public MyService()
{
this.ServiceName = "MyService";
this.CanStop = true;
this.CanPauseAndContinue = false;
this.AutoLog = true;
}

protected override void OnStart(string [] args)
{
// do startup stuff
}

protected override void OnStop()
{
// do shutdown stuff
}

public static void Main()
{
System.ServiceProcess.ServiceBase.Run(new CronService());
}
}

At the top we have to reference two .net library base class. Actually what each class do is
Service base class provide following methods
1. OnStart:
This method is called by Service Control Manager when your service is started.

2. OnStop:
This method is called by Service control manager when your service is stopped.

3. OnPause:
This method is called when your service is paused.

4. OnContinue:
This method is called when your service resumes after being paused.

5. OnShutdown:
This method is called when the system is shutting down.

Installer class.
This class provides custom installation functionality to application. In theory windows service application cannot be started and stop like usual application so we need to configure service control manager by adding set of installers.

Here is sample installer code


using System.ComponentModel;
using System.Configuration.Install;

[RunInstaller(true)]
public class MyServiceInstaller : Installer
{
private ServiceProcessInstaller processInstaller;
private ServiceInstaller serviceInstaller;

public CronInstaller()
{
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();

processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Manual;
serviceInstaller.ServiceName = "MyService";

Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}

How to implement.
Following code shows sample implementation OS onStart method


protected override void OnStart(string[] args)
{
//hur24serviceRef();

_timer.AutoReset = true;
_timer.Interval = 1800000; // // 30 min
//_timer.Interval = 86400000; // // 24hour
//_timer.Interval = 3600000; // 1hour seconds
_timer.Elapsed += rtndoc;
_timer.Start();
}

private void rtndoc(object sender, ElapsedEventArgs e)
{
string filepath = @"C:\FilepathTest\sample.txt";
string time = DateTime.Now.ToString();
System.IO.StreamWriter wri = new System.IO.StreamWriter(filepath, true);
wri.WriteLine("\n" + time+"-dISTRIBUTOR");
wri.Close();

#region pricelist Process

DistributorService.Distributor24.ServiceSoapClient priceli = new Distributor24.ServiceSoapClient();
priceli.InsertDistributorToKandy();

#endregion

}

protected override void OnStop()
{
_timer.Stop();
}

Finally put all these code into file called myService.cs and build it usual way.

How to installed
Following small code shows how to run installed id using CMD

InstallUtil /LogToConsole=true MyService.exe

How to start and stop

net start MyService and net stop MyService.

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.