Develop WINDOWS Services under. net

Source: Internet
Author: User
Microsoft Windows Services (formerly known as NT Services) enable you to create executable applications that can run for a long time in their own Windows sessions. These services can be automatically started when the computer is started. They can be paused and restarted without displaying any user interface. This makes the service very suitable for use on the server, or any time, in order not to affect other users working on the same computer, it needs to be used for a long time to run the function. You can also run the service in a security context different from the logon user's specific user account or default computer account.

Create a Windows Service

When creating a service, you can use the Visual Studio. NET project template called Windows service. This template automatically performs most of your work by referencing appropriate classes and namespaces, setting inheritance from the service base class, and rewriting several methods that you may want to override.

To create a functional service, you must at least:

  • SetServiceNameAttribute.
  • Create a required installer for the service application.
  • RewriteOnStartAndOnStopMethod and specify the code to customize the service behavior.

After adding the installer to the application, the next step is to create an installation project, which will install the compiled project file and run the installation program required to install the service. To create a complete installation project, you must add the output of the Service Project to the installation project, and then add custom operations to install your service.

  1. Create a Windows service project.
  2. In the "properties" window, setServiceNameAttribute. (Note:ServiceNameThe property value must always match the name recorded in the installer class. If you change this property, you must also updateServiceNameAttribute .)
  3. Set all the following attributes to determine the service working mechanism.
    Attribute Set
    CanStop TrueIndicates that the service will accept the request to stop running;FalseIndicates that the service is disabled.
    CanShutDown TrueIndicates that the Service wants to receive a notification when the computer that runs it is disabled so that it can callOnShutDownProcess.
    CanPauseAndContinue TrueIndicates that the service will accept the request to suspend or continue running;FalseThis indicates that the service is not suspended or continues.
    CanHandlePowerEvent TrueIndicates that the service can handle notifications about computer power status changes; false indicates that the service is forbidden to receive notifications about these changes.
    AutoLog

    TrueIndicates that information items are written into the event log of the application when the Service performs operations;FalseIndicates that this function is disabled. (Note:Default Value:True.)

    Note:WhenCanStopOrCanPauseandContinueSetFalseThe Service Control Manager disables the corresponding menu options for stopping, pausing, or resuming the service.

  4. Access the code editor andOnStartAndOnStopProcess.
  5. Override all other methods for which you want to define functions.
  6. Add the installer necessary for the service application.
  7. Select "generate solution" from the "generate" menu to generate a project. (Note:Do not run the project by pressing F5. You cannot run the service project in this way .)

Instance:
Create a Windows service project named MyService and change the class name in Service1.cs and code to the name you want. Here I will use MyService in a unified way;
Using System. Threading;
A backend service Thread, private Thread backThread = null;
Instantiate the Thread in the constructor. this. backThread = new Thread (new ThreadStart (this. Running ));
Add the private void Running () {} Method to the class. Generally, keep the thread in the Running state to handle the work you have arranged for it. For example, based on the messages in the message queue, execute the download task to download the file.
Private void Running ()
{
While (true)
{
// Your processing
Thread. Sleep (5*1000); // For example, Sleep a Thread for 5 seconds.
}
}
Override thread control functions
Protected override void OnStart (string [] args)
{
This. backThread. Start ();
}
Protected override void OnStop ()
{
This. backThread. Abort ();
}
Protected override void OnPause ()
{
This. backThread. Suspend ();
}
Protected override void OnContinue ()
{
This. backThread. Resume ();
}
You can also set the attributes listed in the preceding table as needed.

Right-click the project and choose "add"> "add class"> "Installer class". The name is "Install. cs ".
Add the ServiceInstall and ServiceProcessInstall controls to the view designer of Install. cs. You can set properties for these two controls. For example, you can set service dependencies in the ServiceDependedOn attribute of ServiceInstall.

Generate a solution. The following describes how to install the service.

Install and uninstall services

Install Services manually

  1. Access the directory of compiled executable files in the project.
  2. Use the project output as a parameter to run from the command lineInstallUtil.exe. Enter the following code in the command line:
    installutil yourproject.exe

Manually uninstall the service

  • Use the project output as a parameter to run from the command lineInstallUtil.exe. Enter the following code in the command line:
    installutil /u yourproject.exe
Debug Windows service applications

Because the Service must run from the context of the Service Control Manager rather than from Visual Studio. NET, the debugging service is not as simple as debugging Other Visual Studio Application types. To debug the service, you must first start the service and then attach a debugger to the process in which the service is running. Then, you can use all the standard debugging functions of Visual Studio to debug applications.

Warning do not attach a process unless you know what the process is and know the consequences of appending it to the process or possibly canceling the process. For example, if you attach it to the WinLogon process and stop debugging, the system will pause because the system cannot run without WinLogon.

You can only attach a debugger to a running service. The append process will interrupt the current operation of the service; it does not actually terminate or suspend the service. That is to say, if the service is running at the time of debugging, the service is still in the "started" state technically, but its processing has been suspended.

The process appended to the service enables you to debug most of the service code, but not all. For example, because the service has been started, you cannot use this method to debug the code in the OnStart method of the service, or debug the code in the Main method used to load the service. One way to solve this problem is to create a temporary service in the service application that helps debugging. You can install both services and then start the "virtual" service to load the service process. After the temporary service starts the process, you can use the "debug" menu in Visual Studio. NET to attach it to the service process.

After attaching the process, you can set breakpoints and use these breakpoints to debug the code. When you exit the dialog box used to append the process, it is in debugging mode. You can use the Service Control Manager to start, stop, pause, and continue your service, thus hitting the configured breakpoint. After successful debugging, remove this "virtual" service.

Note that it may be difficult to debug the OnStart method because the Windows Service Manager limits the time for all attempts to start the service to within 30 seconds. When you debug a Windows service application, the Service interacts with the "Windows Service Manager. "Service Manager" by callingOnStartMethod to start the service, and then spend 30 seconds waitingOnStartMethod. If the method is not returned within this period of time, the manager displays an error indicating that the service cannot be started. IfOnStartIf you place a breakpoint in the method and do not pass the breakpoint within 30 seconds, the manager does not start the service.

Debugging Service

  1. Install your services.
  2. You can start a service from the Service Control Manager, server resource manager, or code.
  3. In Visual Studio, select process from the Debug menu ". The "process" dialog box appears.
  4. Click Show System processes ".
  5. In the available processes area, click the service process, and then click Add ". (The system prompts that the process will have the same name as the executable file of the service .) The "attach to process" dialog box appears.
  6. Select any appropriate options and click OK to close the dialog box. (Note that you are in debugging mode .)
  7. Set any breakpoint to be used in the code.
  8. Access Service Control Manager and manipulate your service, and send stop, pause, and continue commands to hit your breakpoint.

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.