How to compile Windows Services

Source: Internet
Author: User

As defined by Microsoft, a service is an executable file that runs for a long time. It does not support user interfaces and runs under special user accounts, it can also run without any user logging on to the computer. By default, the service runs under the system account. Compared with general applications, services run automatically without interaction with users.

In. NET Framework, the classes related to Windows Services are located under the system. serviceprocess namespace. Specifically, the servicebase class provides the basic class for Windows Services, and the services we compile must be derived from this class.

Servicebase contains four methods that can be overloaded: onstart, onstop, onpause, and oncontinue. As the name suggests, these four methods are called when the service is started, stopped, paused, and resumed (the control of the service can be implemented through the control panel, the Service Control Manager implementation under the management tool (or directly enter services in the running. MSC )).

An executable file that carries services can contain multiple services. Each Service corresponds to a class derived from servicebase. Note that running the executable file is different from starting the service. when running the executable file, the constructor of the service class is called to complete the onstart method of the service. Starting a service is just calling the onstart method of the service.

Use the Service Control Manager (services. MSC) can interact with the Service. Correspondingly, two attributes are provided in servicebase to indicate to the manager the control actions supported by the Service: canstop and canpauseandcontinue. When set to true, in the manager, the Service stop, pause, and continue menu are available. Otherwise, the service is unavailable.

In addition, the canshutdown user indicates whether to send a notification to the service when the system is disabled.

Another important class related to Windows Services is serviceinstaller, which is used to install a service. A servicebase corresponds to a serviceinstaller. Note that the installation of the service is carried out through the tool installutil, which will call the install class in the service executable file for service installation.

In general, we generate our own installation class from the install class, and then instantiate the serviceinstaller class (one or more) corresponding to the Service in the constructor) and a serviceprocessinstaller class that indicates the installation process (this class is used to control the installation process, such as specifying the account for running the installation process ). In the installation class, we should specify the runinstallerattribute so that the installutil tool can identify the installation class in the executable file through reflection technology.

The following is a simple service. It writes a message (current time) to the application event record every five seconds. Through this example, you can understand the service compilation and debugging methods:

1. Create a new project named testservice. The project type is Windows service.

2. Change the service code file name to testservice

3. Switch to the Code view of testservice and write the code as follows:

Hide row number copy code? Testservice. CS
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.ServiceProcess;
  7. using System.Text;
  8. using System.Threading;
  9. namespace TestService
  10. {
  11.     public partial class TestService : ServiceBase
  12.     {
  13.         Thread thread;
  14.         public TestService()
  15.         {
  16.             InitializeComponent();
  17.             this.ServiceName = ".Net Test Service";
  18.             
  19.         }
  20.         protected override void OnStart(string[] args)
  21.         {
  22.             Console.WriteLine("The Service Is Runing!");
  23.             if (thread == null)
  24.             {
  25.                 this.thread = new Thread(this.ThreadRun);
  26.             }
  27.             this.thread.IsBackground = true;
  28.             this.thread.Start();
  29.         }
  30.         protected override void OnStop()
  31.         {
  32.             if (this.thread != null)
  33.             {
  34.                 if (this.thread.ThreadState == System.Threading.ThreadState.Running)
  35.                 {
  36.                     this.thread.Abort();
  37.                 }
  38.             }
  39.         }
  40.         private void ThreadRun()
  41.         {
  42.             while (true)
  43.             {
  44.                 Thread.Sleep(5000);
  45.                 EventLog.WriteEntry(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  46.             }
  47.         }
  48.     }
  49. }

4. Create a new class named testinstall. cs. The Code is as follows:

Hide row number copy code? Testinstall. CS
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.ServiceProcess;
  6. using System.Configuration.Install;
  7. using System.ComponentModel;
  8. namespace TestService
  9. {
  10.     [RunInstaller(true)]
  11.     public class TestInstall : Installer
  12.     {
  13.         ServiceProcessInstaller processInstall;
  14.         ServiceInstaller serviceInstall;
  15.         public TestInstall()
  16.         {
  17.             this.processInstall = new ServiceProcessInstaller();
  18.             this.serviceInstall = new ServiceInstaller();
  19.             processInstall.Account = ServiceAccount.LocalSystem;
  20.             this.serviceInstall.ServiceName = ".Net Test Service";
  21.             this.Installers.Add(this.serviceInstall);
  22.             this.Installers.Add(this.processInstall);
  23.         }
  24.     }
  25. }

5. Compile the entire solution

6. Run the installutil command to install the service:

1) enter the Visual Studio 2008 Command Prompt

2) switch the current path to the DEBUG directory of the Project path, for example:

Cd d: \ others \ develop \ CSHARP \ testservice \ bin \ debug

3) install the service and run the following command:

Installutil testservice.exe

4. Start the service and run the input services. MSC. We will see that our service already exists in the service list, named. Net Test Service.

5. Right-click the name to start the service.

6. How can I debug the service? After the service is started, return to Visual Studio, select the attach to process command in the debugging menu, check show processes from all users in the pop-up window, and then find our service process: testservice.exe, select it, and then click attach. After attach, if we add a breakpoint during the threadrun process, the service will be suspended after the next loop arrives and enters the debugging status.

7. In this example, we constantly write records to the application diary. To view this result, you can start the Event Viewer (start to run input eventvwr. MSC), select an application, and the source is. net test service record, which is written by our service process. Double-click to view the event description (the current Runtime is required)

8. Uninstall the service by running the following command (stop the service first through the Service Control Manager ):

Installutil/u testservice.exe

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.