- Практическое руководство. Запись сведений о службах в журнал How to: Log Information About Services
- Включение ведения журнала событий по умолчанию для службы To enable default event logging for your service
- Отключение ведения журнала событий для службы To disable event logging for your service
- Настройка ведения пользовательского журнала To set up logging to a custom log
- How to: Log Information About Services
- To enable default event logging for your service
- To disable event logging for your service
- To set up logging to a custom log
- Учебник. Создание приложения службы Windows Tutorial: Create a Windows service app
- Создание службы Create a service
- Переименование службы Rename the service
- Добавление компонентов в службу Add features to the service
- Добавление возможности работы с настраиваемым журналом событий Add custom event log functionality
- Определение действий при запуске службы Define what occurs when the service starts
- Опрос Polling
- Определение действий при остановке службы Define what occurs when the service is stopped
- Определение других действий для службы Define other actions for the service
- Установка состояния службы Set service status
- Реализация состояния ожидания службы Implement service pending status
- Добавление установщиков в службу Add installers to the service
- Установка параметров запуска (необязательно) (Optional) Set startup parameters
- Добавление параметров запуска To add startup parameters
- Сборка службы Build the service
- Установка службы Install the service
- Запуск и выполнение службы Start and run the service
- Проверка журнала событий для службы Verify the event log output of your service
- Очистка ресурсов Clean up resources
- Следующие шаги Next steps
Практическое руководство. Запись сведений о службах в журнал How to: Log Information About Services
По умолчанию все проекты служб Windows могут взаимодействовать с журналом событий приложения и записывать в него сведения и исключения. By default, all Windows Service projects have the ability to interact with the Application event log and write information and exceptions to it. Чтобы указать, что эта функциональность должна быть в вашем приложении, можно использовать свойство AutoLog . You use the AutoLog property to indicate whether you want this functionality in your application. По умолчанию ведение журнала включено для любой службы, созданной с помощью шаблона проекта службы Windows. By default, logging is turned on for any service you create with the Windows Service project template. Можно использовать статическую форму класса EventLog для записи сведений в журнал, и тогда не потребуется создавать экземпляр компонента EventLog или вручную регистрировать источник. You can use a static form of the EventLog class to write service information to a log without having to create an instance of an EventLog component or manually register a source.
Установщик службы автоматически регистрирует каждую службу в проекте как допустимый источник событий для журнала приложений на компьютере, где установлена служба, если включено ведение журнала. The installer for your service automatically registers each service in your project as a valid source of events with the Application log on the computer where the service is installed, when logging is turned on. Служба записывает сведения каждый раз, когда служба запускается, останавливается, приостанавливается, возобновляется, устанавливается или удаляется. The service logs information each time the service is started, stopped, paused, resumed, installed, or uninstalled. Она также записывает все возникающие ошибки. It also logs any failures that occur. Вам не нужно писать никакой код для записи в журнал при использовании этого поведения по умолчанию; служба обрабатывает это автоматически. You do not need to write any code to write entries to the log when using the default behavior; the service handles this for you automatically.
Если вы хотите выполнять запись в другой журнал событий, отличный от журнала приложения, то необходимо задать для свойства AutoLog значение false , создать собственный пользовательский журнал событий в коде службы и зарегистрировать службу в качестве источника записей для этого журнала. If you want to write to an event log other than the Application log, you must set the AutoLog property to false , create your own custom event log within your services code, and register your service as a valid source of entries for that log. Затем вам придется написать код для выполнения записи в журнал всякий раз, когда происходит интересующее вас действие. You must then write code to record entries to the log whenever an action you’re interested in occurs.
Если вы используете пользовательский журнал событий и настроили службу для записи в этот журнал, не пытайтесь обратиться к этому журналу до установки свойства ServiceName службы в коде. If you use a custom event log and configure your service application to write to it, you must not attempt to access the event log before setting the service’s ServiceName property in your code. Журналу событий нужно значение этого свойства, чтобы зарегистрировать службу в качестве допустимого источника событий. The event log needs this property’s value to register your service as a valid source of events.
Включение ведения журнала событий по умолчанию для службы To enable default event logging for your service
Установите для свойства AutoLog вашего компонента значение true . Set the AutoLog property for your component to true .
По умолчанию для свойства задано значение true . By default, this property is set to true . Вам не нужно задавать это явно, если только вы не создаете более сложную обработку, такую как оценка условия и последующая установка свойства AutoLog в зависимости от результата этого условия. You do not need to set this explicitly unless you are building more complex processing, such as evaluating a condition and then setting the AutoLog property based on the result of that condition.
Отключение ведения журнала событий для службы To disable event logging for your service
Установите для свойства AutoLog вашего компонента значение false . Set the AutoLog property for your component to false .
Настройка ведения пользовательского журнала To set up logging to a custom log
Задайте для свойства AutoLog значение false . Set the AutoLog property to false .
Чтобы использовать пользовательский журнал, необходимо задать в свойстве AutoLog значение false. You must set AutoLog to false in order to use a custom log.
Настройте экземпляр компонента EventLog в приложении службы Windows. Set up an instance of an EventLog component in your Windows Service application.
Создайте пользовательский журнал, вызвав метод CreateEventSource и задав исходную строку и имя файла журнала, который хотите создать. Create a custom log by calling the CreateEventSource method and specifying the source string and the name of the log file you want to create.
Укажите в свойстве Source компонента EventLog исходную строку, созданную на шаге 3. Set the Source property on the EventLog component instance to the source string you created in step 3.
Выполняйте запись в журнал, вызывая метод WriteEntry в экземпляре компонента EventLog . Write your entries by accessing the WriteEntry method on the EventLog component instance.
Следующий код показывает, как настроить ведение пользовательского журнала. The following code shows how to set up logging to a custom log.
В этом примере кода экземпляр компонента EventLog называется eventLog1 ( EventLog1 в Visual Basic). In this code example, an instance of an EventLog component is named eventLog1 ( EventLog1 in Visual Basic). Если на шаге 2 вы создали экземпляр с другим именем, измените код соответствующим образом. If you created an instance with another name in step 2, change the code accordingly.
How to: Log Information About Services
By default, all Windows Service projects have the ability to interact with the Application event log and write information and exceptions to it. You use the AutoLog property to indicate whether you want this functionality in your application. By default, logging is turned on for any service you create with the Windows Service project template. You can use a static form of the EventLog class to write service information to a log without having to create an instance of an EventLog component or manually register a source.
The installer for your service automatically registers each service in your project as a valid source of events with the Application log on the computer where the service is installed, when logging is turned on. The service logs information each time the service is started, stopped, paused, resumed, installed, or uninstalled. It also logs any failures that occur. You do not need to write any code to write entries to the log when using the default behavior; the service handles this for you automatically.
If you want to write to an event log other than the Application log, you must set the AutoLog property to false , create your own custom event log within your services code, and register your service as a valid source of entries for that log. You must then write code to record entries to the log whenever an action you’re interested in occurs.
If you use a custom event log and configure your service application to write to it, you must not attempt to access the event log before setting the service’s ServiceName property in your code. The event log needs this property’s value to register your service as a valid source of events.
To enable default event logging for your service
Set the AutoLog property for your component to true .
By default, this property is set to true . You do not need to set this explicitly unless you are building more complex processing, such as evaluating a condition and then setting the AutoLog property based on the result of that condition.
To disable event logging for your service
Set the AutoLog property for your component to false .
To set up logging to a custom log
Set the AutoLog property to false .
You must set AutoLog to false in order to use a custom log.
Set up an instance of an EventLog component in your Windows Service application.
Create a custom log by calling the CreateEventSource method and specifying the source string and the name of the log file you want to create.
Set the Source property on the EventLog component instance to the source string you created in step 3.
Write your entries by accessing the WriteEntry method on the EventLog component instance.
The following code shows how to set up logging to a custom log.
In this code example, an instance of an EventLog component is named eventLog1 ( EventLog1 in Visual Basic). If you created an instance with another name in step 2, change the code accordingly.
Учебник. Создание приложения службы Windows Tutorial: Create a Windows service app
Из этой статьи вы узнаете, как создать в Visual Studio приложение службы Windows, которое записывает сообщения в журнал событий. This article demonstrates how to create a Windows service app in Visual Studio that writes messages to an event log.
Создание службы Create a service
Для начала создайте проект и настройте значения, необходимые для правильной работы службы. To begin, create the project and set the values that are required for the service to function correctly.
В Visual Studio в меню Файл последовательно выберите пункты Создать > Проект (или нажмите клавиши CTRL+SHIFT+N), чтобы открыть окно Новый проект. From the Visual Studio File menu, select New > Project (or press Ctrl+Shift+N) to open the New Project window.
Найдите и выберите шаблон проекта Служба Windows (.NET Framework) . Navigate to and select the Windows Service (.NET Framework) project template. Чтобы найти его, разверните узел Установленные, затем узел Visual C# или Visual Basic и выберите Рабочий стол Windows. To find it, expand Installed and Visual C# or Visual Basic, then select Windows Desktop. Можно также ввести запрос Служба Windows в поле поиска в правом верхнем углу и нажать клавишу ВВОД. Or, enter Windows Service in the search box on the upper right and press Enter.
Если вы не видите здесь шаблон Служба Windows, попробуйте установить рабочую нагрузку Разработка классических приложений .NET. If you don’t see the Windows Service template, you may need to install the .NET desktop development workload:
В диалоговом окне Новый проект выберите ссылку Открыть установщик Visual Studio. In the New Project dialog, select Open Visual Studio Installer on the lower left. Выберите рабочую нагрузку Разработка классических приложений .NET и нажмите кнопку Изменить. Select the .NET desktop development workload, and then select Modify.
В поле Имя введите MyNewService, а затем нажмите кнопку ОК. For Name, enter MyNewService, and then select OK.
Откроется вкладка Проект (Service1.cs [Проект] или Service1.vb [Проект] ). The Design tab appears (Service1.cs [Design] or Service1.vb [Design]).
Этот шаблон проекта содержит класс компонента с именем Service1 , наследуемый от System.ServiceProcess.ServiceBase. The project template includes a component class named Service1 that inherits from System.ServiceProcess.ServiceBase. В нем собран основной служебный код, в том числе код для запуска службы. It includes much of the basic service code, such as the code to start the service.
Переименование службы Rename the service
Измените имя службы с Service1 на MyNewService. Rename the service from Service1 to MyNewService.
В обозревателе решений выберите файл Service1.cs или Service1.vb, а затем выберите в контекстном меню команду Переименовать. In Solution Explorer, select Service1.cs, or Service1.vb, and choose Rename from the shortcut menu. Переименуйте файл в MyNewService.cs или MyNewService.vb и нажмите клавишу ВВОД. Rename the file to MyNewService.cs, or MyNewService.vb, and then press Enter
Появится всплывающее окно, предлагающее переименовать все ссылки на элемент кода Service1. A pop-up window appears asking whether you would like to rename all references to the code element Service1.
Выберите Да. In the pop-up window, select Yes.
На вкладке Проект выберите в контекстном меню пункт Свойства. In the Design tab, select Properties from the shortcut menu. В окне Свойства измените значение ServiceName на MyNewService. From the Properties window, change the ServiceName value to MyNewService.
В меню Файл выберите команду Сохранить все. Select Save All from the File menu.
Добавление компонентов в службу Add features to the service
В этом разделе к службе Windows будет добавлен настраиваемый журнал событий. In this section, you add a custom event log to the Windows service. Компонент EventLog — это пример типа компонента, который можно добавить в службу Windows. The EventLog component is an example of the type of component you can add to a Windows service.
Добавление возможности работы с настраиваемым журналом событий Add custom event log functionality
В обозревателе решений в контекстном меню для файла MyNewService.cs или MyNewService.vb выберите пункт Показать конструктор. In Solution Explorer, from the shortcut menu for MyNewService.cs, or MyNewService.vb, choose View Designer.
На панели элементов разверните раздел Компоненты и перетащите компонент EventLog на вкладку Service1.cs [Проект] или Service1.vb [Проект] . In Toolbox, expand Components, and then drag the EventLog component to the Service1.cs [Design], or Service1.vb [Design] tab.
В обозревателе решений в контекстном меню для файла MyNewService.cs или MyNewService.vb выберите пункт Просмотреть код. In Solution Explorer, from the shortcut menu for MyNewService.cs, or MyNewService.vb, choose View Code.
Определите пользовательский журнал событий. Define a custom event log. Для C# измените существующий конструктор MyNewService() . Для Visual Basic добавьте конструктор New() . For C#, edit the existing MyNewService() constructor; for Visual Basic, add the New() constructor:
Добавьте оператор using в файл MyNewService.cs (если его еще нет) или оператор Imports в файл MyNewService.vb для пространства имен System.Diagnostics. Add a using statement to MyNewService.cs (if it doesn’t already exist), or an Imports statement MyNewService.vb, for the System.Diagnostics namespace:
В меню Файл выберите команду Сохранить все. Select Save All from the File menu.
Определение действий при запуске службы Define what occurs when the service starts
В редакторе кода для файла MyNewService.cs или MyNewService.vb найдите метод OnStart. Пустое определение метода было автоматически добавлено при создании проекта в Visual Studio. In the code editor for MyNewService.cs or MyNewService.vb, locate the OnStart method; Visual Studio automatically created an empty method definition when you created the project. Добавьте код, с помощью которой запись сохраняется в журнале событий при запуске службы: Add code that writes an entry to the event log when the service starts:
Опрос Polling
Так как приложение службы предполагает длительное время выполнения, оно обычно опрашивает или отслеживает систему. Отслеживание настраивается в методе OnStart. Because a service application is designed to be long-running, it usually polls or monitors the system, which you set up in the OnStart method. После начала работы службы метод OnStart должен возвращать управление операционной системе, чтобы она не блокировалась. The OnStart method must return to the operating system after the service’s operation has begun so that the system isn’t blocked.
Для создания простого механизма опроса используйте компонент System.Timers.Timer. To set up a simple polling mechanism, use the System.Timers.Timer component. Таймер через определенные интервалы времени генерирует событие Elapsed, при возникновении которых служба может выполнять отслеживание. The timer raises an Elapsed event at regular intervals, at which time your service can do its monitoring. Компонент Timer используется следующим образом: You use the Timer component as follows:
- Задайте свойства компонента Timer в методе MyNewService.OnStart . Set the properties of the Timer component in the MyNewService.OnStart method.
- Запустите таймер, вызвав метод Start. Start the timer by calling the Start method.
Настройка механизма опроса. Set up the polling mechanism.
Чтобы настроить механизм опроса, добавьте следующий код в событие MyNewService.OnStart : Add the following code in the MyNewService.OnStart event to set up the polling mechanism:
Добавьте оператор using в файл MyNewService.cs или оператор Imports в файл MyNewService.vb для пространства имен System.Timers. Add a using statement to MyNewService.cs, or an Imports statement to MyNewService.vb, for the System.Timers namespace:
В классе MyNewService добавьте метод OnTimer для обработки события Timer.Elapsed. In the MyNewService class, add the OnTimer method to handle the Timer.Elapsed event:
В класс MyNewService добавьте переменную-член. In the MyNewService class, add a member variable. Она содержит идентификатор следующего события, которое сохраняется в журнале событий. It contains the identifier of the next event to write into the event log:
Задачи можно выполнять с помощью фоновых рабочих потоков, а не выполнять всю работу в основном потоке. Instead of running all your work on the main thread, you can run tasks by using background worker threads. Для получения дополнительной информации см. System.ComponentModel.BackgroundWorker. For more information, see System.ComponentModel.BackgroundWorker.
Определение действий при остановке службы Define what occurs when the service is stopped
Вставьте в метод OnStop строку кода, с помощью которой запись сохраняется в журнале событий при остановке службы: Insert a line of code in the OnStop method that adds an entry to the event log when the service is stopped:
Определение других действий для службы Define other actions for the service
Вы можете переопределить методы OnPause, OnContinue и OnShutdown, добавив дополнительные процессы обработки. You can override the OnPause, OnContinue, and OnShutdown methods to define additional processing for your component.
Следующий код показывает, как можно переопределить метод OnContinue в классе MyNewService : The following code shows how you to override the OnContinue method in the MyNewService class:
Установка состояния службы Set service status
Службы сообщают о своем состоянии диспетчеру служб, чтобы пользователь мог определить, работает ли служба правильно. Services report their status to the Service Control Manager so that a user can tell whether a service is functioning correctly. По умолчанию служба, которая наследуется от ServiceBase, сообщает ограниченный набор состояний, включая SERVICE_STOPPED, SERVICE_PAUSED и SERVICE_RUNNING. By default, a service that inherits from ServiceBase reports a limited set of status settings, which include SERVICE_STOPPED, SERVICE_PAUSED, and SERVICE_RUNNING. Если служба запускается не сразу, полезно обеспечить сообщение состояния SERVICE_START_PENDING. If a service takes a while to start up, it’s useful to report a SERVICE_START_PENDING status.
Состояния ERVICE_START_PENDING и SERVICE_STOP_PENDING можно реализовать путем добавления кода, вызывающего функцию Windows SetServiceStatus. You can implement the SERVICE_START_PENDING and SERVICE_STOP_PENDING status settings by adding code that calls the Windows SetServiceStatus function.
Реализация состояния ожидания службы Implement service pending status
Добавьте оператор using в файл MyNewService.cs или оператор Imports в файл MyNewService.vb для пространства имен System.Runtime.InteropServices. Add a using statement to MyNewService.cs, or an Imports statement to MyNewService.vb, for the System.Runtime.InteropServices namespace:
Добавьте следующий код в файл MyNewService.cs или MyNewService.vb для объявления значений ServiceState и добавления структуры для состояния, которая будет использоваться при вызове неуправляемого кода: Add the following code to MyNewService.cs, or MyNewService.vb, to declare the ServiceState values and to add a structure for the status, which you’ll use in a platform invoke call:
Диспетчер служб использует члены dwWaitHint и dwCheckpoint структуры SERVICE_STATUS, чтобы определить время, в течение которого нужно ожидать запуска или завершения работы службы Windows. The Service Control Manager uses the dwWaitHint and dwCheckpoint members of the SERVICE_STATUS structure to determine how much time to wait for a Windows service to start or shut down. Если методы OnStart и OnStop выполняются долго, служба может запросить больше времени, повторно вызвав функцию SetServiceStatus с увеличенным значением dwCheckPoint . If your OnStart and OnStop methods run long, your service can request more time by calling SetServiceStatus again with an incremented dwCheckPoint value.
В классе MyNewService объявите функцию SetServiceStatus с помощью вызова неуправляемого кода: In the MyNewService class, declare the SetServiceStatus function by using platform invoke:
Для реализации состояния SERVICE_START_PENDING добавьте следующий код в начало метода OnStart: To implement the SERVICE_START_PENDING status, add the following code to the beginning of the OnStart method:
Для установки состояния SERVICE_RUNNING добавьте код в конце метода OnStart : Add code to the end of the OnStart method to set the status to SERVICE_RUNNING:
Если метод OnStop выполняется долго, повторите данную процедуру для OnStop (необязательно). (Optional) If OnStop is a long-running method, repeat this procedure in the OnStop method. Реализуйте состояние SERVICE_STOP_PENDING и обеспечьте возврат состояния SERVICE_STOPPED до того, как метод OnStop вернет управление. Implement the SERVICE_STOP_PENDING status and return the SERVICE_STOPPED status before the OnStop method exits.
Пример: For example:
Добавление установщиков в службу Add installers to the service
Перед тем как запускать службу Windows, ее нужно установить. При этом она регистрируется в диспетчере служб. Before you run a Windows service, you need to install it, which registers it with the Service Control Manager. В проект можно добавить установщики, которые обрабатывают сведения о регистрации. Add installers to your project to handle the registration details.
В обозревателе решений в контекстном меню для файла MyNewService.cs или MyNewService.vb выберите пункт Показать конструктор. In Solution Explorer, from the shortcut menu for MyNewService.cs, or MyNewService.vb, choose View Designer.
В представлении Конструктор щелкните область фона правой кнопкой мыши и выберите в контекстном меню команду Добавить установщик. In the Design view, select the background area, then choose Add Installer from the shortcut menu.
По умолчанию Visual Studio добавляет в проект класс компонента ProjectInstaller , содержащий два установщика. By default, Visual Studio adds a component class named ProjectInstaller , which contains two installers, to your project. Они предназначены для установки службы и связанного со службой процесса. These installers are for your service and for the service’s associated process.
В представлении Конструктор для ProjectInstaller выберите serviceInstaller1 для проекта Visual C# или ServiceInstaller1 для проекта Visual Basic. Затем в контекстном меню выберите пункт Свойства. In the Design view for ProjectInstaller, select serviceInstaller1 for a Visual C# project, or ServiceInstaller1 for a Visual Basic project, then choose Properties from the shortcut menu.
Убедитесь в том, что в окне Свойства свойство ServiceName имеет значение MyNewService. In the Properties window, verify the ServiceName property is set to MyNewService.
Введите для свойства Description какой нибудь текст, например Пример службы. Add text to the Description property, such as A sample service.
Этот текст отображается в столбце Описание в окне Службы и помогает пользователю понять, для чего служба нужна. This text appears in the Description column of the Services window and describes the service to the user.
Введите текст для свойства DisplayName, Add text to the DisplayName property. например Отображаемое имя MyNewService. For example, MyNewService Display Name.
Этот текст отображается в столбце Отображаемое имя в окне Службы. This text appears in the Display Name column of the Services window. Это имя может отличаться от значения свойства ServiceName, которое представляет собой имя, используемое в системе (например, когда вы запускаете службу с помощью команды net start ). This name can be different from the ServiceName property, which is the name the system uses (for example, the name you use for the net start command to start your service).
Выберите для свойства StartType значение Automatic в раскрывающемся списке. Set the StartType property to Automatic from the drop-down list.
В итоге окно Свойства должно выглядеть так: When you’re finished, the Properties windows should look like the following figure:
В представлении Конструктор для ProjectInstaller выберите serviceProcessInstaller1 для проекта Visual C# или ServiceProcessInstaller1 для проекта Visual Basic. Затем в контекстном меню выберите пункт Свойства. In the Design view for ProjectInstaller, choose serviceProcessInstaller1 for a Visual C# project, or ServiceProcessInstaller1 for a Visual Basic project, then choose Properties from the shortcut menu. Выберите для свойства Account значение LocalSystem в раскрывающемся списке. Set the Account property to LocalSystem from the drop-down list.
Это позволит установить и запускать службу от имени локальной системной учетной записи. This setting installs the service and runs it by using the local system account.
У учетной записи LocalSystem имеется множество разрешений, включая разрешение на запись в журнал событий. The LocalSystem account has broad permissions, including the ability to write to the event log. Эту учетную запись следует использовать с осторожностью, поскольку это может увеличить риск атак с помощью вредоносных программ. Use this account with caution, because it might increase your risk of attacks from malicious software. Для других задач следует рассмотреть возможность использования учетной записи LocalService , которая аналогична учетной записи непривилегированного пользователя локального компьютера. Удаленным серверам при этом передаются учетные данные анонимного пользователя. For other tasks, consider using the LocalService account, which acts as a non-privileged user on the local computer and presents anonymous credentials to any remote server. В этом примере произойдет ошибка, если вы попытаетесь использовать учетную запись LocalService , так как для нее требуется разрешение на запись в журнал событий. This example fails if you try to use the LocalService account, because it needs permission to write to the event log.
Дополнительные сведения об установщиках см. в руководстве по добавлению установщиков в приложение-службу. For more information about installers, see How to: Add installers to your service application.
Установка параметров запуска (необязательно) (Optional) Set startup parameters
Прежде чем добавлять параметры запуска, решите, является ли это наилучшим способом передачи информации в службу. Before you decide to add startup parameters, consider whether it’s the best way to pass information to your service. Хотя параметры запуска просты для использования и синтаксического анализа и пользователи могут легко их переопределять, для пользователей их поиск и применение могут оказаться затрудненными (без документации). Although they’re easy to use and parse, and a user can easily override them, they might be harder for a user to discover and use without documentation. Как правило, если вашей службе требуется всего несколько параметров запуска, то следует использовать реестр или файл конфигурации. Generally, if your service requires more than just a few startup parameters, you should use the registry or a configuration file instead.
Служба Windows может принимать аргументы командной строки или параметры запуска. A Windows service can accept command-line arguments, or startup parameters. При добавлении кода в параметры запуска процесса пользователь может запускать службу со своими собственными специальными параметрами из окна свойств службы. When you add code to process startup parameters, a user can start your service with their own custom startup parameters in the service properties window. Однако эти параметры запуска не сохраняются при следующем запуске службы. However, these startup parameters aren’t persisted the next time the service starts. Задать постоянные параметры запуска можно в реестре. To set startup parameters permanently, set them in the registry.
Для каждой службы Windows создается запись в разделе реестра HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services. Each Windows service has a registry entry under the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services subkey. Для хранения информации, к которой может обращаться ваша служба, в разделе службы можно использовать подраздел Parameters. Under each service’s subkey, use the Parameters subkey to store information that your service can access. Файлы конфигурации приложения для службы Windows можно использовать так же, как и для программ других типов. You can use application configuration files for a Windows service the same way you do for other types of programs. Пример кода см. в разделе ConfigurationManager.AppSettings. For sample code, see ConfigurationManager.AppSettings.
Добавление параметров запуска To add startup parameters
Выберите файл Program.cs или MyNewService.Designer.vb, а затем в контекстном меню выберите пункт Просмотреть код. Select Program.cs, or MyNewService.Designer.vb, then choose View Code from the shortcut menu. Измените код метода Main , добавив входной параметр, который будет передаваться в конструктор службы: In the Main method, change the code to add an input parameter and pass it to the service constructor:
В файле MyNewService.cs или MyNewService.vb измените конструктор MyNewService для обработки входного параметра следующим образом: In MyNewService.cs, or MyNewService.vb, change the MyNewService constructor to process the input parameter as follows:
Этот код задает имя источника события и журнала в соответствии с указанными пользователем параметрами запуска. This code sets the event source and log name according to the startup parameters that the user supplies. Если аргументы не заданы, используются значения по умолчанию. If no arguments are supplied, it uses default values.
Чтобы задать аргументы командной строки, добавьте следующий код в класс ProjectInstaller в файле ProjectInstaller.cs или ProjectInstaller.vb: To specify the command-line arguments, add the following code to the ProjectInstaller class in ProjectInstaller.cs, or ProjectInstaller.vb:
Как правило, это значение представляет собой полный путь к исполняемому файлу службы Windows. Typically, this value contains the full path to the executable for the Windows service. Для правильного запуска службы пользователь должен заключить путь и каждый параметр в кавычки. For the service to start up correctly, the user must supply quotation marks for the path and each individual parameter. Чтобы изменить параметры запуска службы Windows, пользователь может настроить параметры в разделе реестра ImagePath. A user can change the parameters in the ImagePath registry entry to change the startup parameters for the Windows service. Однако лучше изменять их программными средствами и создать для пользователей удобный интерфейс для этой возможности, например в виде программы управления или настройки. However, a better way is to change the value programmatically and expose the functionality in a user-friendly way, such as by using a management or configuration utility.
Сборка службы Build the service
В обозревателе решений выберите пункт Свойства в контекстном меню проекта MyNewService. In Solution Explorer, choose Properties from the shortcut menu for the MyNewService project.
Отобразятся страницы свойств для проекта. The property pages for your project appear.
На вкладке Приложение в списке Автоматически запускаемый объект выберите MyNewService.Program (или Sub Main для проекта Visual Basic). On the Application tab, in the Startup object list, choose MyNewService.Program, or Sub Main for Visual Basic projects.
Чтобы выполнить сборку проекта, в обозревателе решений выберите в контекстном меню проекта пункт Сборка (или нажмите клавиши CTRL+SHIFT+B). To build the project, in Solution Explorer, choose Build from the shortcut menu for your project (or press Ctrl+Shift+B).
Установка службы Install the service
После создания службы Windows ее можно установить. Now that you’ve built the Windows service, you can install it. Чтобы установить службу Windows, необходимо иметь разрешения администратора на том компьютере, где выполняется установка. To install a Windows service, you must have administrator credentials on the computer where it’s installed.
Откройте Командную строку разработчика Visual Studio с учетными данными администратора. Open Developer Command Prompt for Visual Studio with administrative credentials.
В командной строке разработчика для Visual Studio перейдите к папке, которая содержит выходные данные проекта (по умолчанию это подкаталог \bin\Debug проекта). In Developer Command Prompt for Visual Studio, navigate to the folder that contains your project’s output (by default, the \bin\Debug subdirectory of your project).
Введите следующую команду: Enter the following command:
Если служба установлена успешно, команда сообщит об успешном выполнении. If the service installs successfully, the command reports success.
Если система не может найти файл installutil.exe, убедитесь в том, что он есть на вашем компьютере. If the system can’t find installutil.exe, make sure that it exists on your computer. Это средство устанавливается вместе с платформой .NET Framework в папке %windir%\Microsoft.NET\Framework[64]\ . This tool is installed with the .NET Framework to the folder %windir%\Microsoft.NET\Framework[64]\ . Например, для 64-разрядной версии по умолчанию используется путь %windir%\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe. For example, the default path for the 64-bit version is %windir%\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.
Если процесс installutil.exe завершается сбоем, найдите причину в журнале установки. If the installutil.exe process fails, check the install log to find out why. По умолчанию журнал находится в той же папке, что и исполняемый файл службы. By default, the log is in the same folder as the service executable. Установка может завершиться сбоем по указанным ниже причинам. The installation can fail if:
- Класс RunInstallerAttribute отсутствует в классе ProjectInstaller . The RunInstallerAttribute class isn’t present on the ProjectInstaller class.
- Значение атрибута отличается от true . The attribute isn’t set to true .
- Класс ProjectInstaller не определен как public . The ProjectInstaller class isn’t defined as public .
Запуск и выполнение службы Start and run the service
В Windows откройте классическое приложение Службы. In Windows, open the Services desktop app. Нажмите клавиши Windows+R, чтобы открыть окно Выполнить, введите services.msc и нажмите клавишу ВВОД или кнопку ОК. Press Windows+R to open the Run box, enter services.msc, and then press Enter or select OK.
Заданное вами отображаемое имя службы отобразится в списке Службы, представленном в алфавитном порядке. You should see your service listed in Services, displayed alphabetically by the display name that you set for it.
Чтобы запустить службу, в ее контекстном меню выберите пункт Запустить. To start the service, choose Start from the service’s shortcut menu.
Чтобы остановить службу, в ее контекстном меню выберите пункт Остановить. To stop the service, choose Stop from the service’s shortcut menu.
Для запуска и остановки службы в командной строке можно использовать команды net start и net stop (необязательно). (Optional) From the command line, use the commands net start and net stop to start and stop your service.
Проверка журнала событий для службы Verify the event log output of your service
В Windows откройте классическое приложение Просмотр событий. In Windows, open the Event Viewer desktop app. Введите строку Просмотр событий в поле поиска Windows и выберите Просмотр событий в результатах поиска. Enter Event Viewer in the Windows search bar, and then select Event Viewer from the search results.
В Visual Studio доступ к журналам событий можно получить, открыв обозреватель сервера в меню Вид (или нажав клавиши CTRL+ALT+S) и развернув узел Журналы событий для локального компьютера. In Visual Studio, you can access event logs by opening Server Explorer from the View menu (or press Ctrl+Alt+S) and expanding the Event Logs node for the local computer.
В средстве просмотра событий разверните узел Журналы приложений и служб. In Event Viewer, expand Applications and Services Logs.
Найдите в списке элемент MyNewLog (или MyLogFile1, если вы использовали процедуру добавления аргументов командной строки) и разверните его. Locate the listing for MyNewLog (or MyLogFile1 if you followed the procedure to add command-line arguments) and expand it. Вы увидите записи для двух действий (запуск и остановка), которые выполнила ваша служба. You should see the entries for the two actions (start and stop) that your service performed.
Очистка ресурсов Clean up resources
Если приложение службы Windows вам больше не нужно, его можно удалить. If you no longer need the Windows service app, you can remove it.
Откройте Командную строку разработчика Visual Studio с учетными данными администратора. Open Developer Command Prompt for Visual Studio with administrative credentials.
В окне Командная строка разработчика для Visual Studio перейдите к папке, которая содержит выходные данные проекта. In the Developer Command Prompt for Visual Studio window, navigate to the folder that contains your project’s output.
Введите следующую команду: Enter the following command:
Если служба удалена успешно, команда сообщит об этом. If the service uninstalls successfully, the command reports that your service was successfully removed. Дополнительные сведения см. в разделе Практическое руководство. Установка и удаление служб. For more information, see How to: Install and uninstall services.
Следующие шаги Next steps
Теперь, после создания службы, можно выполнить указанные ниже действия. Now that you’ve created the service, you can:
Создайте автономную программу установки, с помощью которой другие пользователи могут устанавливать вашу службу Windows. Create a standalone setup program for others to use to install your Windows service. Создать установщик для службы Windows можно с помощью набора инструментов WiX. Use the WiX Toolset to create an installer for a Windows service. Другие идеи можно почерпнуть в статье о создании пакета установщика. For other ideas, see Create an installer package.
Изучите возможности компонента ServiceController, который позволяет отправлять команды в установленную службу. Explore the ServiceController component, which enables you to send commands to the service you’ve installed.
Для создания журнала событий при установке приложения, а не во время его запуска, можно воспользоваться установщиком. Instead of creating the event log when the application runs, use an installer to create an event log when you install the application. В этом случае журнал событий удаляется установщиком при удалении приложения. The event log is deleted by the installer when you uninstall the application. Для получения дополнительной информации см. EventLogInstaller. For more information, see EventLogInstaller.