Windows service Programming

Source: Internet
Author: User

1 Basic Concepts 1.1windows Service Introduction

created in their own An executable application that can run for a long time in a Windows session. These services can be started automatically when the computer starts, can be paused and restarted, and does not display any user interface.

1.2 Where applicable

suitable for use on the server and does not need the interface, the long time stable operation situation.

1.3 How to install and uninstall Services

1) Installation

Use InstallUtil.exe command, execute the install command from the command prompt tool. Specific as follows

First, Execute command CD C:\Windows\Microsoft.NET\Framework\v4.0.30319

Then, execute InstallUtil.exe Path

where path is applied to the service to be installed. Note that Windows Server 2012 uses the following installation command:. \installutil.exe path

2) Uninstall

installutil.exe/u Path

Note thatWindows Server 2012 uses the following installation commands:

. \installutil.exe/u Path

3) How to manage services

Use "Service Control Manager" start, stop, pause, resume, and configure services as shown in the following:

2 Creating a service 2.1 of four methods

using multithreading start, stop, pause, resume

protected override void OnStart (string[] args): Start

protected override void OnStop (): Stop

protected override void OnPause (): Paused

protected override void OnContinue (): Continue

2.2 Adding an installer

The first step is to double-click the Red box position.

The second step, on the following page, right-click.

Popup, click on the red box position

In the third step, the following interface configures the installer.

The parameters of the following two graphs mean:

Account: Accounts type. Four of the public, into

Member name

Description

LocalService

An account that can be used as a non-privileged user on the local computer and provide anonymous credentials to any remote server.

LocalSystem

An account that uses the Service Control Manager, which has many privileges on the local computer and acts as a computer on the network.

NetworkService

An account that provides multiple local privileges and provides credentials to all remote servers for the computer.

User

Define an account on the network for a specific user. Specifying user as Serviceprocessinstaller.account member causes the system to prompt for a valid user name and password when the service is installed, unless you set the value to Username and Password attribute you ServiceProcessInstaller instance.

Delayedautostart: This value indicates whether the service should be postponed before running other auto-started services that cannot start. True to delay the automatic start of the service, otherwise false. The default value is False.

Description: A short comment explaining the role of the service.

DisplayName: Identifies the name of the service.

ServiceName: The name that the system uses to identify this service.

Servicesdependedon: The service that this service relies on.

StartType: How and when to start this service.

Member name

Description

Automatic

Indicates that the service will be started by (or by) the operating system at system startup. If an automatically started service relies on a manually started service, the manually started service will also start automatically when the system starts.

Disabled

Indicates that the service is disabled and therefore cannot be enabled by a user or application.

Manual

Indicates that the service is started manually by the user only (using the Service Control Manager) or the application.

3 Some tricks 3.1 Configuration of service names

Get the service name that is configured in the configuration file, with the following code:

 Public classservicenamesetting {/// <summary>        ///Service Name/// </summary>        /// <returns></returns>         Public Static stringServiceName {Get            {                returnGetappconfigtext (Getconfigpath ("HYMDService.exe.config"),"ServiceName","Hymdservice"); }        }        /// <summary>        ///get the configuration file path/// </summary>/// <param name= "Appconfigname" >application configuration file name</param>        /// <returns></returns>        Private Static stringGetconfigpath (stringappconfigname) {            stringRoot =System.Reflection.Assembly.GetExecutingAssembly ().            Location; returnRoot. Remove (Root. LastIndexOf ('\\') +1) +Appconfigname; }        /// <summary>        ///Get configuration section/// </summary>        /// <param name= "Configpath" >application configuration file path</param>        /// <param name= "Strkeyname" ><appSettings>configuration section Add node key property corresponding value</param>        /// <param name= "DefaultName" >Default service Name</param>        /// <returns></returns>        Private Static stringGetappconfigtext (stringConfigpath,stringStrkeyname,stringdefaultname) {            if(!string. Isnullorwhitespace (Configpath) &&!string. Isnullorwhitespace (Strkeyname)) {using(XmlTextReader tr =NewXmlTextReader (Configpath)) {                     while(tr. Read ()) {if(tr. NodeType = =xmlnodetype.element) {if(tr. Name = ="Add"&& tr. GetAttribute ("Key") ==strkeyname) {                                returnTr. GetAttribute ("value"); }                        }                    }                }            }            returnDefaultName; }}

Attention:

The above code does not use System.configuration.configurationmanager.appsettings[key] Read the configuration file because this mode cannot read the configuration file when the program is started, so use the method used in this article.

3.2 Long tasks paused and resumed

Ideas:

in the The OnPause method will flowcontroller.istopause = True to indicate that the service should be paused. The Flowcontroller.continue method is called in the OnContinue method.

in the code, the location that needs to be paused is called Flowcontroller.pause, when you click on "Pause", issue a Pause command, the program runs to the Flowcontroller.pause method will stop here.

The Pause method uses Autoevent.waitone () to block threads until a signal is received.

The Continue method uses the Autoevent.set () signal to allow the thread to continue execution.

Process controller, the code is as follows:

 Public classFlowcontroller { Public Static BOOLIstopause =false;  Public StaticAutoResetEvent autoevent =NewAutoResetEvent (false); /// <summary>        ///Pause Service/// </summary>         Public Static voidPause (params)        {//processing of parametric params//The recording program is paused.Autoevent.waitone (); }/// <summary>        ///Service continues/// </summary>         Public Static voidContinue (params)        {//processing of parametric params//the logger continues.Autoevent.set (); Istopause=false; }    }

-----------------------------------------------------------------------------------------

Reprint and quote please specify the source.

Time haste, the level is limited, if has the improper place, welcome correction.

Windows service Programming

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.