Introdução aos Aplicativos de Serviço do 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. Para obter mais informações sobre serviços e sessões do Windows, consulte a documentação de Platform SDK no Biblioteca MSDN.
Observação |
---|
The Windows Service template and associated functionality is not available in the Standard Edition of Visual Studio. |
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, or by using Visual Studio's deployment features. You can then use the Services Control Manager to start, stop, pause, resume, and configure your service. Você também pode realizar muitas das mesmas tarefas no serviços nó Server Explorer ou usando o ServiceController classe.
Aplicativos de serviço vs.Outros aplicativos de Visual Studio
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 Como: Depurar aplicativos de serviço do Windows.
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 Como: Adicionar instaladores ao seu aplicativo de serviço.
O Main método seu aplicativo de serviço deve emitir o comando Run para os serviços de seu projeto contém. O Run método carrega os serviços para o O Gerenciador de controle de serviços no servidor apropriado. 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. Para obter mais informações, consulte a documentação do Platform SDK.
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.
Depois que o serviço tiver sido carregado, ele deve ser iniciado. Iniciando o serviço permite que ele comece a funcionar. Você pode iniciar um serviço do O Gerenciador de controle de serviços, da Server Explorer, ou de código, chamando o Start método. O Start método passa o processamento para o aplicativo OnStart método e processa qualquer código que você tenha definido ali.
A running service can exist in this state indefinitely until it is either stopped or paused or until the computer shuts down. Um serviço pode existir em um dos três estados básico: Running, Paused, or Stopped. O serviço também pode relatar o estado de um comando pendente: ContinuePending, PausePending, StartPending, or StopPending. Esses status indicam que um comando foi emitido, como, por exemplo, um comando para pausar um serviço em execução, mas não foi realizado ainda. Você pode consultar a Status para determinar o estado de um serviço ou use o WaitForStatus para executar uma ação quando algum desses estados ocorre.
You can pause, stop, or resume a service from the Services Control Manager, from Server Explorer, or by calling methods in code. Cada uma dessas ações pode chamar um procedimento associado no serviço (OnStop, OnPause, ou OnContinue), no qual você pode definir processamentos adicionais a serem executadas quando o serviço alterar estado.
Types of Services
There are two types of services you can create in Visual Studio using the .NET Framework. Os serviços são o único serviço em um processo são considerados do tipo Win32OwnProcess. Os serviços que compartilham um processo com outro serviço são considerados do tipo Win32ShareProcess. Você pode recuperar o tipo de serviço consultando a ServiceType propriedade.
You might occasionally see other service types if you query existing services that were not created in Visual Studio. Para obter mais informações sobre elas, consulte o ServiceType.
Services and the ServiceController Component
O ServiceController componente é usado para se conectar a um serviço instalado e manipular o seu estado; usando um ServiceController componente, você pode iniciar e interromper um serviço, pausar e continuar o seu funcionamento e enviar comandos personalizados para um serviço. No entanto, você não precisará usar um ServiceController componente quando você cria um aplicativo de serviço. Na verdade, na maioria dos casos seu ServiceController componente deve existir em um aplicativo separado do aplicativo de serviço do Windows que define seu serviço.
For more information, see ServiceController.
Deploying and Installing Services
Visual Studio ships installation components that can install resources associated with your service applications. Installation components register an individual service on the system to which it is being installed and let the Services Control Manager know that the service exists.
After you add installers to your application, the next step is to create a setup project that will install the compiled project files and run the installers needed to install your service. To create a complete setup project, you must add the service project's output to the setup project and then add a custom action to have your service installed. Para obter mais informações sobre projetos de instalação, consulte Setup and Deployment Projects. Para obter mais informações sobre ações personalizadas, consulte Walkthrough: Criando uma ação personalizada.
Requirements
Serviços devem ser criados em um Windows Service o projeto de aplicativo ou em outro.Projeto do NET Framework que cria um arquivo. exe quando compilado e herda a ServiceBase classe.
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 Como: Adicionar instaladores ao seu aplicativo de serviço.
Consulte também
Tarefas
Como: Criar serviços do Windows
Como: Instalar e desinstalar serviços
Como: Depurar aplicativos de serviço do Windows
Demonstra Passo a passo: Criando um Aplicativo Windows Service no Designer de Componentes
Como: Adicionar instaladores ao seu aplicativo de serviço
Walkthrough: Criando uma ação personalizada
Conceitos
Arquitetura de Programação de Aplicativos de Serviço