C # create a Windows Service

Source: Internet
Author: User

1. Introduction to Windows Services:
Windows Services refer to applications that can be opened automatically when the operating system starts. The Windows service can be run without an interactive user logging on to the system, and some processing is performed in the background.

In the past, writing Windows service programs required strong C or C ++ skills from programmers. However, in Visual Studio. NET, you can use C ++, Visual C #, or Visual Basic. Net to easily create a Windows service program. Similarly, you can use any other CLR-compatible language to create a Windows service program. This article introduces how to use Visual C # To create a Windows Service Program for file monitoring step by step, and then describes how to install, test and debug the Windows service program.
Before introducing how to create a Windows service program, I would like to introduce some background knowledge about Windows Services. A Windows Service Program is an executable application that can complete specific functions in a Windows operating system. Although a Windows service program is executable, it does not run as a normal executable file by double-clicking it. It must have a specific startup method.These methods include automatic start and Manual start.For automatically started Windows service programs, they are executed before the user logs on after Windows is started or restarted. As long as you register the corresponding Windows service program to the Service Control Manager (Service
Control Manager), and set its startup category to Automatic startup. For a Windows service program that is manually started, you can use the net start command of the command line tool to start it, or start the corresponding Windows service program through the service item under the management tool in the control panel (see figure 1 ). Similarly, a Windows service program cannot be terminated as a normal application. Because Windows service programs generally do not have a user interface, you need to stop them using the command line tool or the tool shown in the figure below, or make the Windows Service Program stop automatically when the system is disabled. Because Windows service programs do not have a user interface, the user interface-based API functions have little significance for them. To enable a Windows service program to work normally and effectively in a system environment, programmers must implement a series of methods to complete its service functions. Windows service programs have a wide range of applications. Typical Windows service programs include hardware control, application monitoring, system-level applications, diagnostics, reporting, web and file system services.

Open the window service in window7 (right-click "computer"> "manage"> "Computer Management"> "services and applications"), as shown in:

Windows Service Architecture

Operating Windows Services requires 3 programs:

1. Service programs

2. service control procedures

3. service configuration program

The service program itself is used to provide the required functions. The service control program can send control requests to the service, such as start, stop, pause, and continue. You can use the service configuration program to install the service. This means that the service should not only be copied to the file system, but also be written to the Registry and configured as a service .. . NET components do not need to write information into the registry, so you can use the xcopy command to install them. However, registry configuration is required for service installation. In addition, the service configuration program can change the service configuration later.

2. Create a Windows Service Program:
Before introducing how to create a Windows service program, I would like to introduce the namespaces related to Windows Services and the class libraries in the. NET Framework .. The. NET Framework greatly simplifies the process of creating and controlling Windows service programs, thanks to the powerful class libraries in its namespace. The namespaces related to Windows service programs involve system. serviceprocess and system. diagnostics.
To create a basic Windows service program, we only need to use it.. NET Framework. serviceprocess namespace and its four classes: servicebase, serviceinstaller, serviceprocessinstaller, and servicecontroller. The architecture of serviceprocess is shown in figure 2.
The servicebase class defines some functions that can be overloaded by its subclass. With these overloaded functions, the Service Control Manager can control the Windows service program. These functions include onstart (), onstop (), onpause (), and oncontinue. In addition, the subclass of the servicebase class can also overload the oncustomcommand () function to complete some specific operations. By reloading the above functions, we have completed the basic framework of a Windows service program. The methods for reloading these functions are as follows:

 

protected override void OnStart(string[] args){}protected override void OnStop(){}protected override void OnPause(){}protected override void OnContinue(){} 

The servicebase class also provides some attributes that are required by any Widnows service program. The servicename attribute specifies the name of the Windows Service. The system can call the Windows service by using this name. Other applications can also call its service by using this name. The canpauseandcontinue and canstop attributes, as the name suggests, allow pause, recovery, and allow stop.

To make a Windows service program run properly, we need to create a program entry point for it just like creating a general application. In the Windows service program, we also completed this operation in the main () function. First, create a Windows service instance in the main () function. The instance should be a subclass object of the servicebase class, then we call a run () method defined by the base class servicebase class. However, the run () method does not start the Windows service program. We must use the service control manager mentioned earlier to call specific control functions to start the Windows service program, that is, the service will not really start running until the onstart () method of the object is called. If you want to start multiple services in a Windows Service Program at the same time, you only need to define the Instance Object of multiple servicebae class subclasses in the main () function, the method is to create an array object of the servicebase class so that each object corresponds to a pre-defined service.

 

static void Main(){  System.ServiceProcess.ServiceBase[] MyServices;  MyServices = new System.ServiceProcess.ServiceBase[] { new Service1(), new Service2() };  System.ServiceProcess.ServiceBase.Run(MyServices);} 

Iii. Windows service applications (using a timer to write window logs in real time ):
1. Create a Windows Service Project ,:

 

2. Add a counter on the created Project (remember below the system. Timer class). For details, see the http://www.cnblogs.com/wxukie/archive/2008/01/17/1043219.html

Code:

Using system; using system. collections. generic; using system. componentmodel; using system. data; using system. diagnostics; using system. serviceprocess; using system. text; using system. io; namespace myservice {partial class myservice: servicebase {public myservice () {initializecomponent ();} protected override void onstart (string [] ARGs) {This. timer1.enabled = true; EventLog. writeentry ("time1", "window call start");} protected override void onstop () {This. timer1.enabled = false; EventLog. writeentry ("time1", "window call ended");} protected override void onpause () {This. timer1.enabled = false; EventLog. writeentry ("time1", "window call pause");} protected override void oncontinue () {This. timer1.enabled = false; EventLog. writeentry ("time1", "window call recovery");} protected override void onshutdown () {This. timer1.enabled = false; EventLog. writeentry ("time1", "called when window is closed");} private void timerreceivelapsed (Object sender, system. timers. elapsedeventargs e) {EventLog. writeentry ("time1", "window is being called ");}}}

 

The onstart method is called when the Windows service starts.

The onend method is called when the Windows service ends,

Other methods (see more through the automatic prompt function of vs. net.

 

4. Generate a project:

You can select generate from the generate menu to generate a project. (Do not run the project by pressing F5-you cannot run the service project in this way .)

5. Install the service:

1. Access the directory of compiled executable files in the project.

2. Run installutil.exe from the command line using the project output as a parameter (this execution program is in C: "Windows" Microsoft. NET "Framework" v2.0.50727 ).

3. Enter the following code in the command line:
Installutil.exe E: "myservice" myservice "bin" debug "myservice.exe
PS: The Path depends on the executable program location

4. Uninstall the service
Run installutil.exe from the command line.
Installutil.exe E: "myservice" myservice "bin" debug "myservice.exe-u

Now, the entire service has been compiled, compiled, and installed. You can see the service you have compiled in the service of the management tool on the control panel.

You can select generate from the generate menu to generate a project. (Do not run the project by pressing F5-you cannot run the service project in this way .)

From: http://www.oksvn.com/Article/Detail-53.shtml

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.