Use C # To create a Windows Service

Source: Internet
Author: User
The current. the. NET Framework already provides powerful support for the development of Windows Services. You only need to pay attention to the logic to be implemented by the service, rather than how the service is implemented at the underlying layer, compared with the previous use of MFC, It is a qualitative leap. Let's talk about how to implement the most basic windows service and how to debug windows service.
Open VS 2005, click File> New> Project ...., In the Create Project Wizard, select a Windows service template, as shown in:

In the project name input box, enter TestService and click OK. VS generates the most basic code for us. We change the Service name to the expected name, right-click the service file "Service1.cs" automatically generated by vs in solution explorer ", select Rename in the pop-up menu, enter "MyFirstService", and switch to the design view, that is, double-click MyfirstService in solution explorer. cs: in Property Explorer, change the ServiceName attribute to MyFirstService. A running windows service has been created successfully. Let's add some code to test this service. The simplest test method is to add some messages to the windows event log to display the status of our Service.
We need an EventLog component to add information to windows log. In solution explorer, double-click the MyfirstSerice file to switch to the design view, and drag the EventLog component in the toolbox to the design view, the default name of the EventLog component eventLog1 is retained. Select eventLog1, select the Log attribute as Application in property explorer, and enter "MyFirstService" in the Source attribute ". Next, right-click the blank area of the design View and select View Code to switch to the Code View. In the OnStart and OnStop methods, enter the Code to write logs. The Code is as follows:

Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Diagnostics;
Using System. ServiceProcess;
Using System. Text;

Namespace TestService
{
Public partial class MyFirstService: ServiceBase
{
Public MyFirstService ()
{
InitializeComponent ();
}

Protected override void OnStart (string [] args)
{
// TODO: Add code here to start your service.
EventLog1.WriteEntry ("Service start ");
}

Protected override void OnStop ()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
EventLog1.WriteEntry ("Service stop ");
}
}
}

To run this service, we need to perform the following steps:
1. add Installer for our Service, right-click design view, and select Add Installer. VS will Add ProjectInstaller for us. cs, and add components serviceInstaller1 and serviceProcessInstaller1 to ProjectInstaller. Now let's modify their attributes to control Service installation and startup options. In the project installer design view, select serviceProcessInstaller1 and select the Account attribute as LocalSystem to start the Account service. If you want the service to be automatically started when the system starts, select the StartType attribute of serviceInstaller1 as Automatic. If it is manually started, select manaul.
2. Install the serviceprogram intallutil.exe, which is located in C: \ WINDOWS \ Microsoft. NET \ Framework \ v2.0.50727. Click the Start menu and select "run". In the run dialog box, Enter cmd to enter the command line window, and enter cd: \ WINDOWS \ Microsoft. NET \ Framework \ v2.0.50727, enter this directory, and then enter installutil F: \ Programs \ C # \ TestService \ bin \ Debug \ testserveice.exe, the content behind installutil is the path of the executable program generated by our project, which can be modified as needed.
If you set StartType of ServiceInstaller1 to Automatic, the service is running after the service is installed. If StartType is Manual, you need to start it manually. Now, go to "service". To open "service", click "start", point to "Settings", and click "Control Panel ". Click "performance and maintenance" and "Management Tools", and then double-click "service ". You should be able to see our Service MyFirstService. Here, we can start, shut down the service, and set the Service Startup type. Then, let's see if the service has correctly written logs. We need to go to the Event Viewer. To open the Event Viewer, click Start and point to settings ", click control panel ". Click performance and maintenance, click management tools, and double-click event viewer ". As shown in, our message has been successfully written to the system log.

If you do not need this Service, you still use the InstallUtil program to uninstall it. However, after InstallUtil, it is followed by the parameter-u, such as installutil-u F: \ Programs \ C # \ TestService \ bin \ Debug \ testserveice.exe.
The Service debugging method is different from the common program debugging method. Let me introduce it.
1. Build your project
2. Set breakpoints because our Service is very simple and there is no execution logic. Therefore, it makes no sense to set breakpoints. You can write some code for practice. In general, we need another thread to execute the task in our service. You need to set the breakpoint in the thread's Execution Code.
3. Install the service. We will introduce how to install the service.
4. If your Service start type is Manual, you need to start your Service in "Service. In general, if your service is in the development stage, I recommend that you set the Service Startup type to Manual to facilitate debugging, because if the service is running, you will not be able to build the project.
5. In VS, select Debug-> Attach Process... from the menu ...., :

The running processes are listed in. If you cannot find your service, select Show processes from all users. In the Available processes list, select the process TestService where our service is located, and click Attach. If the breakpoint you set is reasonable, the program stops at the breakpoint, next you can perform debugging.

 

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.