What is a Windows service?
Windows service applications are applications that require long-term running. They are especially suitable for server environments. It does not have a user interface and does not produce any visual output. Any user message is written into the Windows event log. When the computer starts, the service automatically starts running. They do not run only when users log on. They can run in any user environment including the system. Through the Service Control Manager, Windows Services are controllable and can be terminated, paused, and started as needed.
Windows Services, formerly NT services, are introduced as part of the Windows NT operating system. They are not in Windows 9x or Windows Me. You need to use an NT-level operating system to run Windows Services, such as Windows NT, Windows 2000 Professional, or Windows 2000 Server. For example, products in the form of Windows Services include Microsoft Exchange and SQL Server, and Windows Time services such as computer clock settings.
Create a Windows Service
The service we are about to create does nothing except demonstration. When the service is started, an entry is registered to a database to indicate that the service has been started. During service running, it regularly creates a database project record at a specified interval. When the service is stopped, the last database record is created. This service automatically registers with the Windows Application log the records when it is successfully started or stopped.
Visual Studio. NET makes creating a Windows Service quite simple. The following describes how to start the demo service program.
1. Create a project
2. Select a Windows service from the list of available project templates
3. The designer opens in design mode.
4. Drag a Timer object from the component table in the toolbox to the design surface (Note: Make sure that Timer is used from the component list rather than from the Windows form List)
5. Set the Timer attribute. The Enabled attribute is False, and the Interval attribute is 30000 milliseconds.
6. Switch to the Code view page (Press F7 or select code from the View menu) and fill in the function for this service.
Composition of Windows Services
In the code behind your class, you will notice that the Windows Service you created expands the System. ServiceProcess. Service class. All Windows Services created in. NET mode must expand this class. It requires your service to reload the following methods. Visual Studio includes these methods by default.
• Dispose-clear any managed and unmanaged resources)
• OnStart-Control Service Startup
• OnStop-Control Service stop
--------------------------------------------------------------------------------
Windows service example
The following is a test case. The service name is Service1 and the black part is automatically generated. The red part is the code I added and the green part is the annotation I added. This case has no other meaning, only insert records into the database.
Using System;
Using System. Collections;
Using System. ComponentModel;
Using System. Data;
Using System. Diagnostics;
Using System. ServiceProcess;
Using System. Configuration. Install;
Using SysData. Db;
Namespace serverTest
{
Public class Service1: System. ServiceProcess. ServiceBase
{
Private System. Timers. Timer timer1;
/// <Summary>
/// Required designer variables.
/// </Summary>
Private System. ComponentModel. Container components = null;
Public Service1 ()
{
// This call is required by the Windows. Forms component designer.
InitializeComponent ();
// TODO: add any initialization after the InitComponent call
}
// Master entry point of the process
Static void Main ()
{
System. ServiceProcess. ServiceBase [] ServicesToRun;
// Multiple user services can be run in the same process. To
// Add another service to this process. Change the downstream service.
// Create another service object. For example,
//
// ServicesToRun = New System. ServiceProcess. ServiceBase [] {new Service1 (), new MySecondUserService ()};
//
ServicesToRun = new System. ServiceProcess. ServiceBase [] {new Service1 ()};
System. ServiceProcess. ServiceBase. Run (ServicesToRun );
}
/// <Summary>
/// The designer supports the required methods-do not use the code editor
/// Modify the content of this method.
/// </Summary>
Private void InitializeComponent ()
{
This. timer1 = new System. Timers. Timer ();
(System. ComponentModel. ISupportInitialize) (this. timer1). BeginInit ();
//
// Timer1
//
This. timer1.Enabled = true;
This. timer1.Interval = 30000;
This. timer1.Elapsed + = new System. Timers. ElapsedEventHandler (this. timerw.elapsed );
//
// Service1
//
This. ServiceName = "Service1 ";
(System. ComponentModel. ISupportInitialize) (this. timer1). EndInit ();
}
/// <Summary>
/// Clear all resources in use.
/// </Summary>
Protected override void Dispose (bool disposing)
{
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}
/// <Summary>
/// Set specific operations so that the service can perform its work.
/// </Summary>
Protected override void OnStart (string [] args)
{
// TODO: Add code here to start the service.
This. timer1.Enabled = true;
This. LogMessage ("Service Started ");
}
/// <Summary>
/// Stop the service.
/// </Summary>
Protected override void OnStop ()
{
// TODO: Add code here to stop the service.
This. timer1.Enabled = false;
This. LogMessage ("Service Stopped ");
}
Private void LogMessage (string xMsg)
{
Try
{
// Insert a record with the Information xMsg to the database. below is the method for adding records to the database class that I wrote in advance. You can also use other methods to write records to the database.
// Db. QuerySQL ("Insert into SysMsg (SysMsg) values ('" + xMsg + "')");
}
Catch
{
// Do not perform any operations
}
}
Private void timerincluelapsed (object sender, System. Timers. ElapsedEventArgs e)
{
LogMessage ("Check service running! ");
}
}
}
--------------------------------------------------------------------------------
Install Windows Services
Windows Services are different from common Windows applications. It is impossible to simply start the Windows service by running an EXE. To install a Windows service, you must use installutil.exe of. NET framework.exe, or use a file deployment project such as Microsoft Installer (MSI.
Add service Installer
It is not enough to create a Windows Service and only use the InstallUtil program to install the service. You must add a service installer to your Windows Service so that InstallUtil or any other installer can know how your service is configured.
1. Switch the service program to the design view.
2. Right-click the design view and select "add installer"
3. Switch to the design view of the newly added ProjectInstaller.
4. Set the attributes of the serviceInstaller1 component:
1) ServiceName = My Sample Service
2) StartType = Automatic
5. Set the attributes of the serviceProcessInstaller1 component
1) Account = LocalSystem
6. Generate a solution
--------------------------------------------------------------------------------
Install Windows Services with InstallUtil
Now that this service has been generated, you need to install it to use it. The following operations will guide you to install your new service.
1. Prompt for opening the Visual Studio. NET command
2. Change the path to the bin "Debug folder location where your project is located (if you compile in Release mode, in the bin" Release folder)
3. Execute the command "installutil.exe MyWindowsService.exe" to register this service and create an appropriate registration item.
Note: Running InstallUtil.exe directly may fail. The prompt is:
'InstallUtil.exe 'is not an internal or external command, or a program or batch file that can be run.
You can find this executable program in C: "WINNT" Microsoft. NET "Framework" v1.1.4322.
4. Right-click "my computer" on the desktop and select "manage" to access the computer management console.
5. In the "services" section of "services and applications", you can find that your Windows services are included in the Service list.
6. Right-click your service and choose start to start your service.
Every time you need to modify the Windows Service, this requires you to uninstall and reinstall the service. However, it is a good habit to ensure that the service management console is closed before you uninstall the service. If this is not the case, you may encounter problems when uninstalling and re-installing Windows Services. If you only uninstall the service, you can run the InstallUtil command to log out of the service. However, you need to add a/u command to the end.
Debug Windows Services
From another perspective, debugging Windows Services is totally different from a common application. More steps are required to debug Windows Services. Services cannot be debugged as long as they are simply executed in the development environment as you do for common applications. The service must be installed and started first. We have done this in the previous section. To facilitate code tracing and debugging, once the service is started, you must use Visual Studio to append the running process (attach ). Remember, any modifications made to your Windows service must be uninstalled and reinstalled.
Append a running Windows Service
To debug the program, some operating instructions for the Windows Service are attached. These operations assume that you have installed the Windows service and it is running.
1. Use Visual Studio to load this project
2. Click the "debug" menu
3. Click the process menu.
4. Ensure that the system process is selected
5. In the list of available processes, locate the process on your Executable File Name and click to select it
6. Click the Add button.
7. Click OK.
8. Click Close.
9. Set a breakpoint in the timerreceivelapsed method and wait for it to execute
Summary
Now you should have a rough understanding of what Windows Services are and how to create, install, and debug them. You can study the functions of Windows Services on your own. These functions include OnPause and OnContinue. The pause and resume capabilities are not enabled by default. You must set them through Windows Service properties.