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
  1. using System;
  2. using System.ServiceProcess;
  3. System.Configuration.Install.Installer;
  4.  
  5.  
  6. public class MyService: ServiceBase
  7. {
  8.   public MyService()
  9.   {
  10.     this.ServiceName = "MyService";
  11.     this.CanStop = true;
  12.     this.CanPauseAndContinue = false;
  13.     this.AutoLog = true;
  14.   }
  15.  
  16.   protected override void OnStart(string [] args)
  17.   {
  18.     // do startup stuff
  19.   }
  20.  
  21.   protected override void OnStop()
  22.   {
  23.    // do shutdown stuff
  24.   }
  25.  
  26.   public static void Main()
  27.   {
  28.    System.ServiceProcess.ServiceBase.Run(new CronService());
  29.   }
  30. }
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
  1. using System.ComponentModel;
  2. using System.Configuration.Install;
  3.  
  4. [RunInstaller(true)]
  5. public class MyServiceInstaller : Installer
  6. {
  7.   private ServiceProcessInstaller processInstaller;
  8.   private ServiceInstaller serviceInstaller;
  9.  
  10.   public CronInstaller()
  11.   {
  12.     processInstaller = new ServiceProcessInstaller();
  13.     serviceInstaller = new ServiceInstaller();
  14.  
  15.     processInstaller.Account = ServiceAccount.LocalSystem;
  16.     serviceInstaller.StartType = ServiceStartMode.Manual;
  17.     serviceInstaller.ServiceName = "MyService";
  18.  
  19.     Installers.Add(serviceInstaller);
  20.     Installers.Add(processInstaller);
  21.   }
  22. }
How to implement. Following code shows sample implementation OS onStart method
  1.         protected override void OnStart(string[] args)
  2.         {
  3.             //hur24serviceRef();
  4.  
  5.             _timer.AutoReset = true;
  6.             _timer.Interval = 1800000;  // // 30 min
  7.             //_timer.Interval = 86400000;  // // 24hour
  8.             //_timer.Interval = 3600000;  // 1hour seconds
  9.             _timer.Elapsed += rtndoc;
  10.             _timer.Start();
  11.         }
  12.  
  13.         private void rtndoc(object sender, ElapsedEventArgs e)
  14.         {
  15.             string filepath = @"C:\FilepathTest\sample.txt";
  16.             string time = DateTime.Now.ToString();
  17.             System.IO.StreamWriter wri = new System.IO.StreamWriter(filepath, true);
  18.             wri.WriteLine("\n" + time+"-dISTRIBUTOR");
  19.             wri.Close();
  20.  
  21.             #region pricelist Process
  22.  
  23.             DistributorService.Distributor24.ServiceSoapClient priceli = new Distributor24.ServiceSoapClient();
  24.             priceli.InsertDistributorToKandy();
  25.  
  26.             #endregion
  27.  
  28.         }
  29.  
  30.         protected override void OnStop()
  31.         {
  32.             _timer.Stop();
  33.         }
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
  1. InstallUtil /LogToConsole=true MyService.exe
How to start and stop
  1. 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