Create the first Windows service

Source: Internet
Author: User

A Windows Service application is a program that runs in the background of the operating system for a long time, and it is particularly suitable for a server environment that does not have a user interface and produces no visual output, and any user output is written back into the Windows event log.

When the computer starts, the service begins to run automatically, and they don't want the user to be logged on.

You can view the services in an existing system by selecting the menu Start-〉 Control Panel-〉 Administrative Tools-〉 services, such as:

Create a Windows service

Switch to Code view modification.

usingSystem;usingSystem.IO;usingsystem.serviceprocess;namespacewindowsservicetest{ Public Partial classHjpservicetest:servicebase {//TimerSystem.Timers.Timer T =NULL;  PublicHjpservicetest () {InitializeComponent (); //Enable pause Recovery            Base. CanPauseAndContinue =true; //executes once every 5 secondst =NewSystem.Timers.Timer ( the); //Whether the setting is executed once (false) or always executed (true);T.autoreset =true; //whether to execute the System.Timers.Timer.Elapsed event;t.enabled =true; //time of arrival execution event (Theout method);t.elapsed + =NewSystem.Timers.ElapsedEventHandler (theout); }            //Start Service Execution        protected Override voidOnStart (string[] args) {              stringState = DateTime.Now.ToString ("YYYY-MM-DD Hh:mm:ss") +"Start";          Writelog (state); }            //Stop Service Execution        protected Override voidOnStop () {stringState = DateTime.Now.ToString ("YYYY-MM-DD Hh:mm:ss") +"Stop";          Writelog (state); }            //Recovery Service Execution        protected Override voidOnContinue () {stringState = DateTime.Now.ToString ("YYYY-MM-DD Hh:mm:ss") +"continue to";              Writelog (state);          T.start (); }            //Pause Service Execution        protected Override voidOnPause () {stringState = DateTime.Now.ToString ("YYYY-MM-DD Hh:mm:ss") +"Pause";            Writelog (state);          T.stop (); }               Public voidWritelog (stringstr) {              using(StreamWriter SW = File.appendtext (@"D:\service.txt") ) {SW.                  WriteLine (str); Sw.              Flush (); }          }             Public voidTheout (Objectsource, System.Timers.ElapsedEventArgs E) {Writelog ("theout:"+ DateTime.Now.ToString ("YYYY-MM-DD Hh:mm:ss")); }      }}

Explanation: OnStart and OnStop are the event action methods that occur after the server starts and stops, respectively. Defines a timer that executes once every 5 seconds (Theout method) because the pause Recovery feature is not enabled by default, You need to set the CanPauseAndContinue property to enable this feature while overriding the OnStop and OnContinue methods to add your own logic code.

Switch the service program HjpServiceTest.cs to view mode, right-click Design view to select the Add Installer option, and then automatically add a ProjectInstaller.cs to the project.

Such as

Open ProjectInstaller, modify ServiceInstaller1 Component Properties

description= My Service Memo service remarks description

Displayname= My service-friendly name

Servicename=hjpservicetest Install server name

Starttype=automatic Service Type

After the Ümanual service is installed, it must be started manually.

Üautomatic the service will start automatically every time the computer restarts.

The üdisabled service could not be started.

and design the properties of the ServiceProcessInstaller1 Account=localsystem

Run compilation, a simple Windows service has been developed to complete.

Installing the Window Service

Install command: InstallUtil.exe WindowsServiceTest.exe

InstallUtil exists path is: C:\WINDOWS\Microsoft.NET\Framework\. NET version number

Copy the InstallUtil.exe in the C:\WINDOWS\Microsoft.Net\Framework\ version number path to the Bin/debug or Bin/release folder and run the command directly in the Command line window

InstallUtil.exe WindowsServiceTest.exe, register this service in the system and make it a suitable registration key, such as:

Then, in the Window service list, start the Hjpservicetest service

Uninstalling the Window service

Command: InstallUtil.exe windowsservicetest.exe/u

If you modify this service, but the path does not need to re-register the service, directly stop the service, and then overwrite the original file with the new file, if the path changes, you should uninstall the service, and then reinstall the service.

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

Window Service Application Architecture

The. NET Framework provides more support for Windows services under namespace System.ServiceProcess.

The include classes are as follows:

ServiceBase base class for all window services

ServiceController an instance of this class represents a specific Windows service

Servicecontrollerpermission used to control the use rights of ServiceController

ServiceInstaller used to perform the installation of Windows services

ServiceProcessInstaller is used to perform the installation of a Windows service, unlike the above class, which can represent a process that can execute a Windows service.

ServiceBase class

ServiceBase Method:

Method

Describe

Run ()

Running a Windows service

OnContinue ()

Continue to perform service

Oncustomcommand ()

To issue custom directives to Windows services

OnPause ()

Pausing a running Windows service

Onpowerevent ()

When the power state of the computer changes is called

OnShutdown ()

When the system closes the bar with OnStart () Start a Windows service

OnStop ()

End a Windows service

ServiceBase Properties:

Property

Describe

AutoLog

Indicates whether to start, end, pause, continue, etc instructions to write to the event log

Canhandlepowerevent

Indicates whether the service supports power events

CanPauseAndContinue

Indicates whether the service supports pause and resume functionality

CanShutdown

Indicates whether the service supports the shutdown feature

CanStop

Indicates whether the service supports structural features

EventLog

The application's time log

ServiceName

The service name

ServiceController class

The service control class, which controls the specific behavior of Windows services, can control both local Windows services and Windows services that can control remote.

Methods of Servicecontroler:

Method

Describe

Getdivices ()

Get a device drive service on a computer

GetServices ()

Get a non-device drive service on the compute

Close ()

Used to disconnect the service and free resources occupied by the service controller

Continue ()

Services that continue to be paused

Excutecommand ()

Execute a custom command on the service

Pause ()

Pause Service

Refresh ()

Update for all properties

Start ()

Start the service

Stop ()

Stop Service

WaitForStatus ()

Wait for service to reach the specified state

ServiceController Property

Property Describe
CanPauseAndContinue Indicates whether the service can be stopped
CanShutdown Indicates whether the service can be notified when the system shuts down, CanStop indicates whether the server can be stopped
Dependentservices Represents a device associated with a service
DisplayName Represents the name that the service controller binds to
MachineName Indicates the name of the computer on which the service resides
ServiceName Represents the service name of the binding
ServiceType Represents the type of service referenced by the controller
Servicesdependedon Indicates that the service relies on the Ude service collection status to indicate the service state referenced by the controller

ServiceInstaller class

Properties of the ServiceInstaller

Property Describe
DisplayName Display Name
ServiceName Represents the service name, which must be the same name as the Windows service that installer will install
Servicedependon An array of service names to be used by the service
StartType Represents the startup characteristics of the installed service, either automatic,manual or disable, which defaults to manual

ServiceInstaller Events
Method Event
Afterinstaller () Occurs after the install method is called
Afterrollback () Occurs after calling rollback
Afteruninstall () Occurs after calling the Uninstall method
Beforeinstall () Occurs before the install method is called
Beforerollback () Occurs before the Rollback method is called
Beforeuninstall () Occurs before the uninstall method is called
Committed () Occurs after the Commit method is called
Committing () Occurs before the Commit method is called

ServiceProcessInstaller class

The Windows service for installing ServiceBase inheritance, which is the same as the basic work done by all the services in an executable program

ServiceProcessInstaller Property

Property Describe
Account Current user account running the service
HelpText Help information given in the Service installation options
Password Current account password to run the service
UserName User name of the current account running the service

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

Windows Services Debugging

VS Open Myserivcelog Project

Start the Myservicelog service inside the management tools-〉 Service

Click the debug-〉 of vs to attach to the process, as

In the Available Processes list, select the executable file name of the service you want to tune

Click the Attach button to enter the debug state

Set a breakpoint in the Timer1_elapsed method and wait for it to execute, and the breakpoint will be automatically started when the service executes to that point.

Create the first Windows service

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.