- Introduction to Windows Service Applications
- Service Applications vs. Other Visual Studio Applications
- Service Lifetime
- Types of Services
- Services and the ServiceController Component
- Requirements
- Develop Windows service apps
- In this section
- Related sections
- Разработка приложений службы Windows Develop Windows service apps
- Содержание раздела In this section
- Связанные разделы Related sections
- Службы Windows
- Создание службы для Windows
Introduction to Windows Service Applications
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. 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. You could write a Windows Service application that listens to the performance counter data, deploy the application, and begin collecting and analyzing data.
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.
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. You can also accomplish many of these same tasks in the Services node in Server Explorer or by using the ServiceController class.
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. 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. For more information, see How to: Debug Windows Service Applications.
Unlike some types of projects, you must create installation components for service applications. 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.
The Main method for your service application must issue the Run command for the services your project contains. The Run method loads the services into the Services Control Manager on the appropriate server. 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 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. 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. Similarly, error messages should be logged in the Windows event log rather than raised in the user interface.
The Windows service classes supported by the .NET Framework do not support interaction with interactive stations, that is, the logged-on user. The .NET Framework also does not include classes that represent stations and desktops. If your Windows service must interact with other stations, you will need to access the unmanaged Windows API. For more information, see the Windows SDK documentation.
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. In some cases, it may be more appropriate to write a Windows application that runs under the control of the user.
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. 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. You can start a service from the Services Control Manager, from Server Explorer, or from code by calling the Start method. 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. A service can exist in one of three basic states: Running, Paused, or Stopped. 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. 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. 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
There are two types of services you can create in Visual Studio using the .NET Framework. Services that are the only service in a process are assigned the type Win32OwnProcess. Services that share a process with another service are assigned the type Win32ShareProcess. You can retrieve the service type by querying the ServiceType property.
You might occasionally see other service types if you query existing services that were not created in Visual Studio. For more information on these, see the ServiceType.
Services and the ServiceController Component
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. However, you do not need to use a ServiceController component when you create a service application. In fact, in most cases your ServiceController component should exist in a separate application from the Windows service application that defines your service.
For more information, see ServiceController.
Requirements
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.
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.
Develop Windows service apps
Using Visual Studio or the .NET Framework SDK, you can easily create services by creating an application that is installed as a service. This type of application is called a Windows service. With framework features, you can create services, install them, and start, stop, and otherwise control their behavior.
In Visual Studio you can create a service in managed code in Visual C# or Visual Basic, which can interoperate with existing C++ code if required. Or, you can create a Windows service in native C++ by using the ATL Project Wizard.
In this section
Provides an overview of Windows service applications, the lifetime of a service, and how service applications differ from other common project types.
Provides an example of creating a service in Visual Basic and Visual C#.
Explains the language elements used in service programming.
Describes the process of creating and configuring Windows services using the Windows service project template.
Related sections
ServiceBase — Describes the major features of the ServiceBase class, which is used to create services.
ServiceProcessInstaller — Describes the features of the ServiceProcessInstaller class, which is used along with the ServiceInstaller class to install and uninstall your services.
ServiceInstaller — Describes the features of the ServiceInstaller class, which is used along with the ServiceProcessInstaller class to install and uninstall your service.
Create Projects from Templates — Describes the projects types used in this chapter and how to choose between them.
Разработка приложений службы Windows Develop Windows service apps
С помощью Visual Studio или пакета SDK для .NET Framework можно легко создавать службы. Просто создайте приложение, которое устанавливается как служба. Using Visual Studio or the .NET Framework SDK, you can easily create services by creating an application that is installed as a service. Такие приложения называются службами Windows. This type of application is called a Windows service. Используя компоненты платформы, можно создавать, устанавливать, запускать, останавливать и администрировать службы. With framework features, you can create services, install them, and start, stop, and otherwise control their behavior.
В Visual Studio можно создать службы с помощью управляемого кода на Visual C# или Visual Basic, который при необходимости может взаимодействовать с существующим кодом C++. In Visual Studio you can create a service in managed code in Visual C# or Visual Basic, which can interoperate with existing C++ code if required. Или можно создать службу Windows на машинном языке C++ с помощью мастера проектов ATL. Or, you can create a Windows service in native C++ by using the ATL Project Wizard.
Содержание раздела In this section
Сведения о приложениях служб Windows, времени существования служб и отличиях приложений служб от распространенных типов проектов. Provides an overview of Windows service applications, the lifetime of a service, and how service applications differ from other common project types.
Пример создания службы на Visual Basic и Visual C#. Provides an example of creating a service in Visual Basic and Visual C#.
Описание элементов языка, используемых при создании служб. Explains the language elements used in service programming.
Создание и настройка служб Windows с помощью шаблона проекта службы Windows. Describes the process of creating and configuring Windows services using the Windows service project template.
Связанные разделы Related sections
ServiceBase — описываются основные характеристики класса ServiceBase, который используется для создания служб. ServiceBase — Describes the major features of the ServiceBase class, which is used to create services.
ServiceProcessInstaller — описываются возможности класса ServiceProcessInstaller, который используется вместе с классом ServiceInstaller для установки и удаления службы. ServiceProcessInstaller — Describes the features of the ServiceProcessInstaller class, which is used along with the ServiceInstaller class to install and uninstall your services.
ServiceInstaller — описываются возможности класса ServiceInstaller, который используется вместе с классом ServiceProcessInstaller для установки и удаления службы. ServiceInstaller — Describes the features of the ServiceInstaller class, which is used along with the ServiceProcessInstaller class to install and uninstall your service.
Create Projects from Templates (Создание проектов на основе шаблонов) — описываются типы проектов, которые используются в этом разделе, и способ их выбора. Create Projects from Templates — Describes the projects types used in this chapter and how to choose between them.
Службы Windows
Создание службы для Windows
Одним из важнейших компонентов ОС Windows являются службы. Фактически это отдельные приложения, которые не имеют графического интерфейса и которые выполняют различные задачи в фоновом режиме. Службы могут быть запущены при старте операционной системы, так и в любой другой момент работы пользователя. Распространенным примером служб являются различные веб-серверы, которые в фоновом режиме прослушивают определенный порт на наличие подключений, и если подключения имеются, то взаимодействуют с ними. Это могут быть также различные вспомогательные сервисы обновлений для других установленных программ, которые обращаются к серверу, чтобы узнать, есть ли новая версия приложения. В общем то мы можем открыть панель служб и сами увидеть все установленные и запущенные службы:
Рассмотрим, как создавать свои службы в C#. В качестве реализуемой задачи выберем наблюдение за изменениями в определенной папке в файловой системе. Теперь создадим для ее выполнения службу.
Вначале создадим новый проект, который будет иметь тип Windows Service . Назовем проект FileWatcherService:
После этого Visual Studio генерирует проект, который имеет все необходимое. Хотя в принципе нам необязательно выбирать именно этот тип проекта, можно было бы создать проект библиотеки классов, и затем в нем определить все необходимые классы.
Итак, новый проект выглядит следующим образом:
Здесь также есть файл Program.cs и есть собственно узел службы Service1.cs .
Служба представляет обычное приложение, но она не запускаетс сама по себе. Все вызовы и обращения к ней проходят через менеджер управления службами (Service Control Manager или SCM). Когда служба запускается автоматически при старте системы или вручную, то SCM обращается к методу Main в классе Program:
Метод Main по умолчанию определен таким образом, чтобы запускать сразу несколько служб, которые определены в массиве ServicesToRun. Однако по умолчанию проект содержит только одну службу Service1. Сам запуск производится с помощью метода Run: ServiceBase.Run(ServicesToRun) .
Сама запускаемая служба представлена узлом Service1.cs. Однако на самом деле это не простой файл кода. Если мы откроем этот узел, то увидим в нем файл дизайнера службы Service1.Designer.cs и класс Service1.
Класс Service1 собственно представляет службу. По умолчанию он имеет следующий код:
Класс службы должен наследоваться от базового класса ServiceBase . Этот класс определяет ряд методов, важнейшие из которых метод OnStart() , который запускает действия, выпоняемые службой, и метод OnStop() , останавливающий службу.
После того, как SCM вызовет метод Main и зарегистрирует службу, происходит непосредственный ее вызов через запуск метода OnStart.
Когда в консоли служб или через командную строку мы посылаем команду на остановку службы, то SCM обращается к методу OnStop для ее остановки.
Кроме этих двух методов в классе службы можно переопределить еще несколько методов базового класса ServiceBase:
OnPause : вызывается при приостановке службы
OnContinue : вызывается при возобновлении работы службы после ее приостановки
OnShutdown : вызывается при завершении работы Windows
OnPowerEvent : вызывается при изменении режима электропитания
OnCustomCommand : вызывается при получении службой пользовательской команды от Менеджера Управления Службами (Service Control Manager / SCM)
В конструкторе класса Service1 вызывается метод InitializeComponent() , который определен в файле дизайнера Service1.Designer.cs:
Единственное, что надо в нем отметить, это установка названия службы (свойство ServiceName):
Это то название, которое будет отображаться в консоли служб после установки данной службы. Мы можем его изменить, а можем и оставить как есть.
Теперь изменим код службы следующим образом:
Ключевым классом, который инкапсулирует всю функциональность, является класс Logger. С помощью объекта FileSystemWatcher он будет вести мониторинг изменений в папке D://Temp. В методе Start() устанавливается, что мы будем отслеживать изменения через объект FileSystemWatcher. И вся работа будет идти, пока булевая переменная enabled равна true . А метод Stop() позволит завершить работу класса.
События FileSystemWatcher позволяют отслеживать все изменения в наблюдаемой папке. При этом будет вестись запись изменений в файл templog.txt. Чтобы не было гонки ресурсов за файл templog.txt, в который вносятся записи об изменениях, процедура записи блокируется заглушкой lock(obj) .
В итоге после создания, изменения, переименования и удаления файл лога будет содержать что-то наподобие:
В самом классе службы Service1 в конструкторе устанавливается ряд опций:
В методе OnStart() для запуска объекта Logger вызывется новый поток:
Новый поток нужен, так как текущий поток обрабатывает только команды SCM и должен возвращаться из метода OnStart как можно быстрее.
Когда от менеджера SCM поступает команда на остановку службы, срабатывает метод OnStop, который вызывает метод logger.Stop() . Дополнительная задержка позволит потоку логгера остановиться:
Однако самого класса службы еще недостаточно. Нам необходимо еще создать устанощик службы.