This article will share with you how to use the C # language to develop system services.
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:
Testservice. CS [http://www.xueit.com]
Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. diagnostics;
Using system. serviceprocess;
Using system. text;
Using system. Threading;
Namespace testservice
{
Public partial class testservice: servicebase
{
Thread thread;
Public testservice ()
{
Initializecomponent ();
This. servicename = ". Net Test Service ";
}
Protected override void onstart (string [] ARGs)
{
Console. writeline ("the service is runing! ");
If (thread = NULL)
{
This. Thread = new thread (this. threadrun );
}
This. thread. isbackground = true;
This. thread. Start ();
}
Protected override void onstop ()
{
If (this. thread! = NULL)
{
If (this. thread. threadstate = system. Threading. threadstate. Running)
{
This. thread. Abort ();
}
}
}
Private void threadrun ()
{
While (true)
{
Thread. Sleep (5000 );
EventLog. writeentry (datetime. Now. tostring ("yyyy-mm-dd hh: mm: SS "));
}
}
}
}
4. Create a new class named testinstall. cs. The Code is as follows:
Code [http://www.xueit.com]
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using system. serviceprocess;
Using system. configuration. Install;
Using system. componentmodel;
Namespace testservice
{
[Runinstaller (true)]
Public class testinstall: Installer
{
Serviceprocessinstaller processinstall;
Serviceinstaller serviceinstall;
Public testinstall ()
{
This. processinstall = new serviceprocessinstaller ();
This. serviceinstall = new serviceinstaller ();
Processinstall. Account = serviceaccount. LocalSystem;
This. serviceinstall. servicename = ". Net Test Service ";
This. installers. Add (this. serviceinstall );
This. installers. Add (this. processinstall );
}
}
}
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