Windows Services Getting Started Guide

Source: Internet
Author: User

Original address: http://www.cnblogs.com/LoveJenny/archive/2013/03/05/2943691.html

There are a lot of times when we need to create Windows Service. This article can be considered as a starter guide, hope to help beginners.

To create a Windows service, first select the Windows Services project, such as:

Here I want to create a Windows service that performs some tasks on a timed basis.

Public partial class service1:servicebase{public    Service1 ()    {        InitializeComponent ();    }    protected override void OnStart (string[] args)    {    }    protected override void OnStop ()    {    }}

OnStart: When the service starts, it executes,

OnStop: Execution when service is stopped

In order to perform the task regularly, I modified the code as follows:

namespace timewindowsservice{public    partial class Service1:servicebase    {        System.Timers.Timer Timer = null;        Public Service1 ()        {            InitializeComponent ();        }        protected override void OnStart (string[] args)        {            timer = new System.Timers.Timer ();            Timer. Elapsed + = timer_elapsed;            Timer. Interval = +;            Timer. Start ();        }        void Timer_elapsed (object sender, System.Timers.ElapsedEventArgs e)        {            Console.WriteLine ("Time Elapsed");        }        protected override void OnStop ()        {            if (timer! = null)            {                timer. Stop ();}}}    

Press F5 to run the code, you will be prompted:

This means that we must first use Installutil.exe to install the service.

Of course you can open the command line and enter a command to install the service, but here I'm going to use external tools to execute InstallUtil.exe.

Where the command is: C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe

Click OK to find a installservice command.

Click on the Installservice, you can see the screen flashed, and then the past, it is obvious because our command error.

Note that when we add installservice, we choose to, so even if there is an error message, it will blink.

The command to modify Installservice is as follows:

Run Installservice again and you can see:

This represents Installservice time error, can't find the file, we hope it's looking for TimeWindowsService.exe,

And not \bin\debug\timewindowsservice.

So the correct setting of the Installservice command should be the following:

Save, then run, with the following results:

The installation is still not successful because there is no installer.

There are a lot of tutorials that will tell you that you need to add a class like this: Http://www.cnblogs.com/jjstar/articles/20353.aspx

Using system.collections;using system.configuration.install;using system.serviceprocess;using System.componentmodel;namespace windowsservice1{//<summary>//Myinstall Summary description. </summary>  //[Runinstaller (True)] public class Myinstall:installer  {  private ServiceInstaller ServiceInstaller;  Private ServiceProcessInstaller Processinstaller;  Public Myinstall ()  {   Processinstaller = new ServiceProcessInstaller ();   ServiceInstaller = new ServiceInstaller ();   Processinstaller.account = Serviceaccount.localsystem;   Serviceinstaller.starttype = servicestartmode.automatic;   Serviceinstaller.servicename = "WindowsService1";   Installers.add (ServiceInstaller);   Installers.add (Processinstaller);  } }}

For someone with a bad memory, it's easy to ask the question: Is there a shortcut key for vs? And, of course, VS offers.

Click on the Service1.cs design page, Add the installer , and VS will automatically generate a installer class for you.

The classes added are:

ServiceProcessInstaller1:

Installs an executable file that contains the classes that extend System.ServiceProcess.ServiceBase. This class is called by the installation utility (such as InstallUtil.exe) when the service application is installed.

SERVICEINSTALL1:

Installs a class that extends System.ServiceProcess.ServiceBase to implement the service. This class is called by the installation utility when the service application is installed.

Careful readers look at their attributes and know where the difference is.

For simplicity, set account to LocalSystem.

OK, the installer has been finished, then the above Installservice bar, note to compile the program AH.

You can see that the installation service has been successfully installed.

From the Task Manager, you can also see the services installed:

OK, then press F5 to debug it, but:

The prompt box still appears, and it is clear that we cannot press F5 to debug the Windows service .

There are many articles that describe how to debug a Windows service.

1: For example this article: Http://www.cnblogs.com/downmoon/archive/2009/09/16/1567643.html, the Attachprocess method used.

Sometimes, however, the service cannot start because of various reasons, or the service stops automatically for some reason, so it is not easy to attach to the process to debug.

2: There are some ways to modify the code, such as:

To add a Debugonstart method

public void Debugonstart ()        {this            . OnStart (null);        }        protected override void OnStart (string[] args)        {            timer = new System.Timers.Timer ();            Timer. Elapsed + = timer_elapsed;            Timer. Interval = +;            Timer. Start ();        }

Then modify the main function as follows:

static void Main ()        {            //servicebase[] servicestorun;            ServicesToRun = new servicebase[]             //{             //    new Service1 ()             //};            Servicebase.run (ServicesToRun);            New Service1 (). Debugonstart ();        }

The effect is as follows:

3: In the constructor use Thread.Sleep. Then quickly attach to the process.

In this way, the service will take 10 seconds to start, with 10 seconds to be " attached to the process ".

One of my favorite ways:

void Timer_elapsed (object sender, System.Timers.ElapsedEventArgs e)        {            if (! debugger.isattached)            {                debugger.launch ();            }            Console.WriteLine ("Time Elapsed");        }

This will prompt you when you start the service:

After clicking OK:

This way, you can add the above statement at any time, anywhere you need to debug.

Specific can refer to the Debugger class.

Reference article: Http://www.codeproject.com/Articles/19914/How-to-debug-a-Windows-Service-and-not-die-in-the

Windows Services Getting Started Guide

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.