Windows 服务应用程序介绍Introduction to Windows Service Applications

Microsoft Windows 服务(过去称为 NT 服务)允许用户创建可在其自身的 Windows 会话中长时间运行的可执行应用程序。Microsoft Windows services, formerly known as NT services, enable you to create long-running executable applications that run in their own Windows sessions. 这些服务可在计算机启动时自动启动,可以暂停和重启,并且不显示任何用户界面。These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface. 这些功能使服务非常适合在服务器上使用,或者需要长时间运行的功能(不会影响在同一台计算机上工作的其他用户)的情况。These features make services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer. 还可以在与登录用户或默认计算机帐户不同的特定用户帐户的安全性上下文中运行服务。You can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account. 有关服务和 Windows 会话的详细信息,请参阅 Windows SDK 文档。For more information about services and Windows sessions, see the Windows SDK documentation.

可以通过创建作为服务安装的应用程序来轻松创建服务。You can easily create services by creating an application that is installed as a service. 例如,假设你想监视性能计数器数据并对阈值作出响应。For example, suppose you want to monitor performance counter data and react to threshold values. 可以编写一个侦听性能计数器数据的 Windows 服务应用程序,部署该应用程序并开始收集和分析数据。You could write a Windows Service application that listens to the performance counter data, deploy the application, and begin collecting and analyzing data.

可以将服务创建为 Microsoft Visual Studio 项目,并在其中定义代码,以控制可以将哪些命令发送到服务以及在收到这些命令时应采取的操作。You create your service as a Microsoft Visual Studio project, defining code within it that controls what commands can be sent to the service and what actions should be taken when those commands are received. 可以发送到服务的命令包括启动、暂停、恢复和停止服务,还可以执行自定义命令。Commands that can be sent to a service include starting, pausing, resuming, and stopping the service; you can also execute custom commands.

在创建和生成应用程序之后,可以通过运行命令行实用程序 InstallUtil.exe 并将该路径传递给服务的可执行文件来安装它。After you create and build the application, you can install it by running the command-line utility InstallUtil.exe and passing the path to the service's executable file. 然后,可以使用服务控制管理器来启动、停止、暂停、恢复和配置服务。You can then use the Services Control Manager to start, stop, pause, resume, and configure your service. 还可以在“服务器资源管理器”的“服务”节点中或使用 ServiceController 类完成许多相同的任务。You can also accomplish many of these same tasks in the Services node in Server Explorer or by using the ServiceController class.

服务应用程序与其他 Visual Studio 应用程序Service Applications vs. Other Visual Studio Applications

服务应用程序与许多其他项目类型的运行方式存在以下几个方面的不同:Service applications function differently from many other project types in several ways:

  • 在项目能够以有意义的方式运行之前,服务应用程序项目创建的已编译可执行文件必须安装在服务器上。The compiled executable file that a service application project creates must be installed on the server before the project can function in a meaningful way. 无法通过按 F5 或 F11 来调试或运行服务应用程序;无法立即运行服务或单步执行其代码。You cannot debug or run a service application by pressing F5 or F11; you cannot immediately run a service or step into its code. 相反,必须安装并启动服务,然后将调试程序附加到服务进程。Instead, you must install and start your service, and then attach a debugger to the service's process. 有关详细信息,请参阅如何:调试 Windows 服务应用程序For more information, see How to: Debug Windows Service Applications.

  • 与某些项目类型不同,你必须为服务应用程序创建安装组件。Unlike some types of projects, you must create installation components for service applications. 安装组件在服务器上安装并注册该服务,并使用 Windows 服务控制管理器为服务创建条目。The installation components install and register the service on the server and create an entry for your service with the Windows Services Control Manager. 有关详细信息,请参阅如何:将安装程序添加到服务应用程序For more information, see How to: Add Installers to Your Service Application.

  • 服务应用程序的 Main 方法必须为项目包含的服务发出 Run 命令。The Main method for your service application must issue the Run command for the services your project contains. Run 方法将服务加载到相应服务器上的服务控制管理器中。The Run method loads the services into the Services Control Manager on the appropriate server. 如果使用 Windows 服务项目模板,则会自动为你编写此方法。If you use the Windows Services project template, this method is written for you automatically. 请注意,加载服务与启动服务不同。Note that loading a service is not the same thing as starting the service. 有关详细信息,请参阅下面的“服务生存期”。See "Service Lifetime" below for more information.

  • Windows 服务应用程序在不同于登录用户的交互式工作站的窗口站中运行。Windows Service applications run in a different window station than the interactive station of the logged-on user. 窗口站是一个安全对象,它包含一个剪贴板、一个全局原子集和一组桌面对象。A window station is a secure object that contains a Clipboard, a set of global atoms, and a group of desktop objects. 由于 Windows 服务站不是交互式工作站,因此从 Windows 服务应用程序中引发的对话框将不会显示,并且可能导致程序停止响应。Because the station of the Windows service is not an interactive station, dialog boxes raised from within a Windows service application will not be seen and may cause your program to stop responding. 同样,错误消息应记录在 Windows 事件日志中,而不是在用户界面中引发。Similarly, error messages should be logged in the Windows event log rather than raised in the user interface.

    .NET Framework 支持的 Windows 服务类不支持与交互式工作站(即登录用户)的交互。The Windows service classes supported by the .NET Framework do not support interaction with interactive stations, that is, the logged-on user. .NET Framework 也不包括表示工作站和桌面的类。The .NET Framework also does not include classes that represent stations and desktops. 如果 Windows 服务必须与其他工作站进行交互,则需要访问非管理的 Windows API。If your Windows service must interact with other stations, you will need to access the unmanaged Windows API. 有关详细信息,请参阅 Windows SDK 文档。For more information, see the Windows SDK documentation.

    Windows 服务与用户或其他工作站的交互必须经过精心设计,以便包括各种场景(如没有登录用户或用户具有一组意外的桌面对象)。The interaction of the Windows service with the user or other stations must be carefully designed to include scenarios such as there being no logged on user, or the user having an unexpected set of desktop objects. 在某些情况下,编写在用户控制下运行的 Windows 应用程序可能更合适。In some cases, it may be more appropriate to write a Windows application that runs under the control of the user.

  • Windows 服务应用程序在其自己的安全上下文中运行,并在用户登录安装这些应用程序的 Windows 计算机之前启动。Windows service applications run in their own security context and are started before the user logs into the Windows computer on which they are installed. 应仔细规划要在哪个用户帐户中运行服务;在系统帐户下运行的服务具有比用户帐户更多的权限和特权。You should plan carefully what user account to run the service within; a service running under the system account has more permissions and privileges than a user account.

服务生存期Service Lifetime

一项服务在其生存期内会经历几个内部状态。A service goes through several internal states in its lifetime. 首先,服务会安装到它将在其上运行的系统上。First, the service is installed onto the system on which it will run. 此过程执行服务项目的安装程序,并将该服务加载到该计算机的服务控制管理器中。This process executes the installers for the service project and loads the service into the Services Control Manager for that computer. 服务控制管理器是 Windows 提供的用于管理服务的中央实用程序。The Services Control Manager is the central utility provided by Windows to administer services.

必须在服务加载完成后启动它。After the service has been loaded, it must be started. 启动该服务以允许它开始运行。Starting the service allows it to begin functioning. 可以从服务“服务控制管理器”、“服务器资源管理器”,或从通过调用 Start 方法的代码来启动服务。You can start a service from the Services Control Manager, from Server Explorer, or from code by calling the Start method. Start 方法将处理进程传递给应用程序的 OnStart 方法,并处理在那里定义的任何代码。The Start method passes processing to the application's OnStart method and processes any code you have defined there.

正在运行的服务可以在此状态下无限期地存在,直到它停止或暂停,或者直到计算机关闭。A running service can exist in this state indefinitely until it is either stopped or paused or until the computer shuts down. 服务可以三种基本状态之一存在:RunningPausedStoppedA service can exist in one of three basic states: Running, Paused, or Stopped. 该服务还可以报告挂起命令的状态:ContinuePendingPausePendingStartPendingStopPendingThe service can also report the state of a pending command: ContinuePending, PausePending, StartPending, or StopPending. 这些状态指示命令已发出(例如,暂停正在运行的服务的命令),但尚未执行。These statuses indicate that a command has been issued, such as a command to pause a running service, but has not been carried out yet. 可以查询 Status 以确定服务所处的状态,或者在出现其中任一状态时使用 WaitForStatus 执行操作。You can query the Status to determine what state a service is in, or use the WaitForStatus to carry out an action when any of these states occurs.

可以从“服务控制管理器”、“服务器资源管理器”,或通过调用代码中的方法来暂停、停止或恢复服务。You can pause, stop, or resume a service from the Services Control Manager, from Server Explorer, or by calling methods in code. 其中的每个操作都可以调用服务中的相关过程(OnStopOnPauseOnContinue),可以在其中定义在服务更改状态时执行的其他处理进程。Each of these actions can call an associated procedure in the service (OnStop, OnPause, or OnContinue), in which you can define additional processing to be performed when the service changes state.

服务类型Types of Services

可以使用 .NET Framework 在 Visual Studio 中创建两种服务类型。There are two types of services you can create in Visual Studio using the .NET Framework. 作为进程中唯一服务的服务将分配类型 Win32OwnProcessServices that are the only service in a process are assigned the type Win32OwnProcess. 与其他服务共享进程的服务将分配类型 Win32ShareProcessServices that share a process with another service are assigned the type Win32ShareProcess. 可以通过查询 ServiceType 属性来检索服务类型。You can retrieve the service type by querying the ServiceType property.

如果查询未在 Visual Studio 中创建的现有服务,则可能偶尔会看到其他服务类型。You might occasionally see other service types if you query existing services that were not created in Visual Studio. 有关这些服务类型的更多信息,请参阅 ServiceTypeFor more information on these, see the ServiceType.

服务和 ServiceController 组件Services and the ServiceController Component

ServiceController 组件用于连接到已安装的服务并操纵其状态;可以使用 ServiceController 组件启动和停止服务,暂停并继续其运行,并将自定义命令发送到服务。The ServiceController component is used to connect to an installed service and manipulate its state; using a ServiceController component, you can start and stop a service, pause and continue its functioning, and send custom commands to a service. 但是,在创建服务应用程序时,无需使用 ServiceController 组件。However, you do not need to use a ServiceController component when you create a service application. 事实上,在大多数情况下,ServiceController 组件应存在于定义服务的 Windows 服务应用程序的单独应用程序中。In fact, in most cases your ServiceController component should exist in a separate application from the Windows service application that defines your service.

有关更多信息,请参见ServiceControllerFor more information, see ServiceController.

要求Requirements

  • 必须在 Windows 服务应用程序项目或其他 .NET Framework(启用了在生成并从 ServiceBase 类继承时创建 .exe 文件的项目)中创建服务。Services must be created in a Windows Service application project or another .NET Framework–enabled project that creates an .exe file when built and inherits from the ServiceBase class.

  • 包含 Windows 服务的项目必须具有项目及其服务的安装组件。Projects containing Windows services must have installation components for the project and its services. 这可以通过“属性”窗口轻松完成。This can be easily accomplished from the Properties window. 有关详细信息,请参阅如何:将安装程序添加到服务应用程序For more information, see How to: Add Installers to Your Service Application.

请参阅See Also

Windows 服务应用程序Windows Service Applications
服务应用程序编程体系结构Service Application Programming Architecture
如何:创建 Windows 服务How to: Create Windows Services
如何:安装和卸载服务How to: Install and Uninstall Services
如何:启动服务How to: Start Services
如何:调试 Windows 服务应用程序How to: Debug Windows Service Applications
演练:在组件设计器中创建 Windows 服务应用程序Walkthrough: Creating a Windows Service Application in the Component Designer
如何:将安装程序添加到服务应用程序How to: Add Installers to Your Service Application