- Hosting in Windows Process Activation Service
- Elements of the WAS Addressing Model
- Знакомство с приложениями служб Windows Introduction to Windows Service Applications
- Приложения-службы и другие приложения Visual Studio Service Applications vs. Other Visual Studio Applications
- Время существования службы Service Lifetime
- Типы служб Types of Services
- Службы и компонент ServiceController Services and the ServiceController Component
- Требования Requirements
Hosting in Windows Process Activation Service
The Windows Process Activation Service (WAS) manages the activation and lifetime of the worker processes that contain applications that host Windows Communication Foundation (WCF) services. The WAS process model generalizes the IIS 6.0 process model for the HTTP server by removing the dependency on HTTP. This allows WCF services to use both HTTP and non-HTTP protocols, such as Net.TCP, in a hosting environment that supports message-based activation and offers the ability to host a large number of applications on a given machine.
For more information about building a WCF service that runs in the WAS hosting environment, see How to: Host a WCF Service in WAS.
The WAS process model provides several features that enable applications to be hosted in a way that is more robust, more manageable, and that uses resources efficiently:
Message-based activation of applications and worker process applications start and stop dynamically in response to incoming work items that arrive using HTTP and non-HTTP network protocols.
Robust application and worker process recycling to maintain the health of running applications.
Centralized application configuration and management.
Allows applications to take advantage of the IIS process model without requiring the deployment footprint of a full IIS installation.
Windows Server AppFabric works with IIS 7.0 and Windows Process Activation Service (WAS) to provide a rich application hosting environment for NET4 WCF and WF services. These benefits include process life-cycle management, process recycling, shared hosting, rapid failure protection, process orphaning, on-demand activation, and health monitoring. For detailed information, see AppFabric Hosting Features and AppFabric Hosting Concepts.
Elements of the WAS Addressing Model
Applications have Uniform Resource Identifier (URI) addresses, which are the code units whose lifetime and execution environment are managed by the server. A single WAS server instance can be home to many different applications. Servers organize applications into groups called sites. Within a site, applications are arranged in a hierarchical manner that reflects the structure of the URIs that serve as their external addresses.
Application addresses have two parts: a base URI prefix and an application-specific, relative address (path), which provide the external address for an application when joined together. The base URI prefix is constructed from the site binding and is used for all the applications under the site. Application addresses are then constructed by taking application-specific path fragments (such as, «/applicationOne») and appending them to the base URI prefix (for example, «net.tcp://localhost») to arrive at the full application URI.
The following table illustrates several possible addressing scenarios for WAS sites with both HTTP and non-HTTP site bindings.
Знакомство с приложениями служб 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 для приложения службы должен выдать команду запуска для служб, которые содержит проект. 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.
Классы службы Windows, поддерживаемые платформой .NET Framework, не поддерживают взаимодействие с интерактивными станциями, т. е. станциями вошедшего в систему пользователя. 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 должна взаимодействовать с другими станциями, нужно получить доступ к неуправляемому API Windows. 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. Есть три основных состояния службы: Running, Paused и Stopped. A service can exist in one of three basic states: Running, Paused, or Stopped. Служба также может сообщать состояние ожидания выполнения команды: ContinuePending, PausePending, StartPending или StopPending. The 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. Каждое из этих действий вызывает соответствующую процедуру в службе (OnStop, OnPause или OnContinue), в которой можно определить дополнительную обработку на случай изменения состояния службы. 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
Есть два типа служб, которые можно создать в Visual Studio с помощью .NET Framework. There are two types of services you can create in Visual Studio using the .NET Framework. Службам, которые являются единственными службами в процессе, назначается тип Win32OwnProcess. Services that are the only service in a process are assigned the type Win32OwnProcess. Службам, которые включены в процесс вместе с другими службами, назначается тип Win32ShareProcess. Services 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. Дополнительные сведения см. здесь: ServiceType. For 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.
Для получения дополнительной информации см. ServiceController. For more information, see ServiceController.
Требования Requirements
Службы должны создаваться в проекте приложения-службы Windows или другом проекте с поддержкой .NET Framework, который создает исполняемый файл при сборке и наследуется от класса ServiceBase. 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.