- Практическое руководство. Установка и удаление служб Windows How to: Install and uninstall Windows services
- Установка с помощью программы InstallUtil.exe Install using InstallUtil.exe utility
- Удаление с помощью служебной программы InstallUtil.exe Uninstall using InstallUtil.exe utility
- Установка с помощью PowerShell Install using PowerShell
- Удаление с помощью PowerShell Uninstall using PowerShell
- Знакомство с приложениями служб 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
Практическое руководство. Установка и удаление служб Windows How to: Install and uninstall Windows services
Если вы разрабатываете службу Windows с помощью .NET Framework, вы можете быстро установить приложение службы с помощью служебной программы командной строки InstallUtil.exe или PowerShell. If you’re developing a Windows service with the .NET Framework, you can quickly install your service app by using the InstallUtil.exe command-line utility or PowerShell. Если вы являетесь разработчиком и хотите создать службу Windows, которую пользователи могут устанавливать и удалять, можно использовать набор инструментов WiX или коммерческие средства, такие как Advanced Installer, InstallShield или другие. Developers who want to release a Windows service that users can install and uninstall can use the free WiX Toolset or commercial tools like Advanced Installer, InstallShield, or others. См. сведения о создании пакета установщика (классическое приложение Windows). For more information, see Create an installer package (Windows desktop).
Если вы хотите удалить службу на своем компьютере, не выполняйте процедуру, описанную в этой статье. If you want to uninstall a service from your computer, don’t follow the steps in this article. Вместо этого определите, какая программа (или программный пакет) установила эту службу, а затем выберите Приложения в параметрах, чтобы удалить эту программу. Instead, find out which program or software package installed the service, and then choose Apps in Settings to uninstall that program. Следует отметить, что многие службы являются составной частью ОС Windows. Если их удалить, это может привести к нестабильной работе системы. Note that many services are integral parts of Windows; if you remove them, you might cause system instability.
Чтобы использовать процедуру, описанную в этой статье, сначала необходимо добавить установщик службы в свою службу Windows. To use the steps in this article, you first need to add a service installer to your Windows service. Дополнительные сведения см. в разделе Пошаговое руководство: создание диспетчера служб Windows. For more information, see Walkthrough: Creating a Windows service app.
Проекты служб Windows нельзя запускать непосредственно из среды разработки Visual Studio путем нажатия клавиши F5. You can’t run Windows service projects directly from the Visual Studio development environment by pressing F5. Перед запуском проекта необходимо установить службу в проекте. Before you can run the project, you must install the service in the project.
Запустите обозреватель сервера и убедитесь, что служба установлена или удалена. You can use Server Explorer to verify that you’ve installed or uninstalled your service.
Установка с помощью программы InstallUtil.exe Install using InstallUtil.exe utility
В меню Пуск выберите каталог Visual Studio и затем Командная строка разработчика для VS . From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .
Появится командная строка разработчика для Visual Studio. The Developer Command Prompt for Visual Studio appears.
Откройте каталог, где находится скомпилированный исполняемый файл вашего проекта. Access the directory where your project’s compiled executable file is located.
Запустите InstallUtil.exe из командной строки, указав исполняемый файл проекта в качестве параметра: Run InstallUtil.exe from the command prompt with your project’s executable as a parameter:
Если вы используете командную строку разработчика для Visual Studio, системный путь должен указывать на файл InstallUtil.exe. If you’re using the Developer Command Prompt for Visual Studio, InstallUtil.exe should be on the system path. Если это не так, можно добавить его в путь или использовать полный путь для его вызова. Otherwise, you can add it to the path, or use the fully qualified path to invoke it. Этот инструмент устанавливается вместе с платформой .NET Framework в папку %WINDIR%\Microsoft.NET\Framework[64]\ . This tool is installed with the .NET Framework in %WINDIR%\Microsoft.NET\Framework[64]\ .
Пример: For example:
- Для 32-разрядной версии .NET Framework 4 или 4.5 и более поздних версий: если каталог установки Windows — C:\Windows, по умолчанию используется путь C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe. For the 32-bit version of the .NET Framework 4 or 4.5 and later, if your Windows installation directory is C:\Windows, the default path is C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe.
- Для 64-разрядной версии .NET Framework 4 или 4.5 и более поздних версий: по умолчанию используется путь C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe. For the 64-bit version of the .NET Framework 4 or 4.5 and later, the default path is C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.
Удаление с помощью служебной программы InstallUtil.exe Uninstall using InstallUtil.exe utility
В меню Пуск выберите каталог Visual Studio и затем Командная строка разработчика для VS . From the Start menu, select the Visual Studio directory, then select Developer Command Prompt for VS .
Появится командная строка разработчика для Visual Studio. The Developer Command Prompt for Visual Studio appears.
Запустите InstallUtil.exe из командной строки, указав выходные данные проекта в качестве параметра: Run InstallUtil.exe from the command prompt with your project’s output as a parameter:
После удаления исполняемого файла для службы сама служба может по-прежнему присутствовать в реестре. After the executable for a service is deleted, the service might still be present in the registry. В этом случае удалить запись службы из реестра можно с помощью команды sc delete. If that’s the case, use the command sc delete to remove the entry for the service from the registry.
Установка с помощью PowerShell Install using PowerShell
В меню Пуск выберите Каталог Windows PowerShell и Windows PowerShell. From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.
Откройте каталог, где находится скомпилированный исполняемый файл вашего проекта. Access the directory where your project’s compiled executable file is located.
Выполните командлет New-Service, указав в качестве параметров выходные данные проекта и имя службы. Run the New-Service cmdlet with the with your project’s output and a service name as parameters:
Удаление с помощью PowerShell Uninstall using PowerShell
В меню Пуск выберите Каталог Windows PowerShell и Windows PowerShell. From the Start menu, select the Windows PowerShell directory, then select Windows PowerShell.
Выполните командлет Remove-Service, указав в качестве параметра имя службы. Run the Remove-Service cmdlet with the name of your service as parameter:
После удаления исполняемого файла для службы сама служба может по-прежнему присутствовать в реестре. After the executable for a service is deleted, the service might still be present in the registry. В этом случае удалить запись службы из реестра можно с помощью команды sc delete. If that’s the case, use the command sc delete to remove the entry for the service from the registry.
Знакомство с приложениями служб 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.