ServiceController Classe
Definição
Representa um serviço Windows e permite que você se conecte a um serviço em execução ou parado, manipule-o ou obtenha informações sobre ele.Represents a Windows service and allows you to connect to a running or stopped service, manipulate it, or get information about it.
public ref class ServiceController : System::ComponentModel::Component
public ref class ServiceController : IDisposable
public class ServiceController : System.ComponentModel.Component
public class ServiceController : IDisposable
[System.ServiceProcess.ServiceProcessDescription("ServiceControllerDesc")]
public class ServiceController : System.ComponentModel.Component
type ServiceController = class
inherit Component
type ServiceController = class
interface IDisposable
[<System.ServiceProcess.ServiceProcessDescription("ServiceControllerDesc")>]
type ServiceController = class
inherit Component
Public Class ServiceController
Inherits Component
Public Class ServiceController
Implements IDisposable
- Herança
- Herança
-
ServiceController
- Atributos
- Implementações
Exemplos
O exemplo a seguir demonstra o uso da ServiceController classe para controlar o SimpleService exemplo de serviço.The following example demonstrates the use of the ServiceController class to control the SimpleService service example.
using System;
using System.ServiceProcess;
using System.Diagnostics;
using System.Threading;
namespace ServiceControllerSample
{
class Program
{
public enum SimpleServiceCustomCommands
{ StopWorker = 128, RestartWorker, CheckWorker };
static void Main(string[] args)
{
ServiceController[] scServices;
scServices = ServiceController.GetServices();
foreach (ServiceController scTemp in scServices)
{
if (scTemp.ServiceName == "Simple Service")
{
// Display properties for the Simple Service sample
// from the ServiceBase example.
ServiceController sc = new ServiceController("Simple Service");
Console.WriteLine("Status = " + sc.Status);
Console.WriteLine("Can Pause and Continue = " + sc.CanPauseAndContinue);
Console.WriteLine("Can ShutDown = " + sc.CanShutdown);
Console.WriteLine("Can Stop = " + sc.CanStop);
if (sc.Status == ServiceControllerStatus.Stopped)
{
sc.Start();
while (sc.Status == ServiceControllerStatus.Stopped)
{
Thread.Sleep(1000);
sc.Refresh();
}
}
// Issue custom commands to the service
// enum SimpleServiceCustomCommands
// { StopWorker = 128, RestartWorker, CheckWorker };
sc.ExecuteCommand((int)SimpleServiceCustomCommands.StopWorker);
sc.ExecuteCommand((int)SimpleServiceCustomCommands.RestartWorker);
sc.Pause();
while (sc.Status != ServiceControllerStatus.Paused)
{
Thread.Sleep(1000);
sc.Refresh();
}
Console.WriteLine("Status = " + sc.Status);
sc.Continue();
while (sc.Status == ServiceControllerStatus.Paused)
{
Thread.Sleep(1000);
sc.Refresh();
}
Console.WriteLine("Status = " + sc.Status);
sc.Stop();
while (sc.Status != ServiceControllerStatus.Stopped)
{
Thread.Sleep(1000);
sc.Refresh();
}
Console.WriteLine("Status = " + sc.Status);
String[] argArray = new string[] { "ServiceController arg1", "ServiceController arg2" };
sc.Start(argArray);
while (sc.Status == ServiceControllerStatus.Stopped)
{
Thread.Sleep(1000);
sc.Refresh();
}
Console.WriteLine("Status = " + sc.Status);
// Display the event log entries for the custom commands
// and the start arguments.
EventLog el = new EventLog("Application");
EventLogEntryCollection elec = el.Entries;
foreach (EventLogEntry ele in elec)
{
if (ele.Source.IndexOf("SimpleService.OnCustomCommand") >= 0 |
ele.Source.IndexOf("SimpleService.Arguments") >= 0)
Console.WriteLine(ele.Message);
}
}
}
}
}
}
// This sample displays the following output if the Simple Service
// sample is running:
//Status = Running
//Can Pause and Continue = True
//Can ShutDown = True
//Can Stop = True
//Status = Paused
//Status = Running
//Status = Stopped
//Status = Running
//4:14:49 PM - Custom command received: 128
//4:14:49 PM - Custom command received: 129
//ServiceController arg1
//ServiceController arg2
Imports System.ServiceProcess
Imports System.Diagnostics
Imports System.Threading
Class Program
Public Enum SimpleServiceCustomCommands
StopWorker = 128
RestartWorker
CheckWorker
End Enum 'SimpleServiceCustomCommands
Shared Sub Main(ByVal args() As String)
Dim scServices() As ServiceController
scServices = ServiceController.GetServices()
Dim scTemp As ServiceController
For Each scTemp In scServices
If scTemp.ServiceName = "Simple Service" Then
' Display properties for the Simple Service sample
' from the ServiceBase example
Dim sc As New ServiceController("Simple Service")
Console.WriteLine("Status = " + sc.Status.ToString())
Console.WriteLine("Can Pause and Continue = " + _
sc.CanPauseAndContinue.ToString())
Console.WriteLine("Can ShutDown = " + sc.CanShutdown.ToString())
Console.WriteLine("Can Stop = " + sc.CanStop.ToString())
If sc.Status = ServiceControllerStatus.Stopped Then
sc.Start()
While sc.Status = ServiceControllerStatus.Stopped
Thread.Sleep(1000)
sc.Refresh()
End While
End If
' Issue custom commands to the service
' enum SimpleServiceCustomCommands
' { StopWorker = 128, RestartWorker, CheckWorker };
sc.ExecuteCommand(Fix(SimpleServiceCustomCommands.StopWorker))
sc.ExecuteCommand(Fix(SimpleServiceCustomCommands.RestartWorker))
sc.Pause()
While sc.Status <> ServiceControllerStatus.Paused
Thread.Sleep(1000)
sc.Refresh()
End While
Console.WriteLine("Status = " + sc.Status.ToString())
sc.Continue()
While sc.Status = ServiceControllerStatus.Paused
Thread.Sleep(1000)
sc.Refresh()
End While
Console.WriteLine("Status = " + sc.Status.ToString())
sc.Stop()
While sc.Status <> ServiceControllerStatus.Stopped
Thread.Sleep(1000)
sc.Refresh()
End While
Console.WriteLine("Status = " + sc.Status.ToString())
Dim argArray() As String = {"ServiceController arg1", "ServiceController arg2"}
sc.Start(argArray)
While sc.Status = ServiceControllerStatus.Stopped
Thread.Sleep(1000)
sc.Refresh()
End While
Console.WriteLine("Status = " + sc.Status.ToString())
' Display the event log entries for the custom commands
' and the start arguments.
Dim el As New EventLog("Application")
Dim elec As EventLogEntryCollection = el.Entries
Dim ele As EventLogEntry
For Each ele In elec
If ele.Source.IndexOf("SimpleService.OnCustomCommand") >= 0 Or ele.Source.IndexOf("SimpleService.Arguments") >= 0 Then
Console.WriteLine(ele.Message)
End If
Next ele
End If
Next scTemp
End Sub
End Class
' This sample displays the following output if the Simple Service
' sample is running:
'Status = Running
'Can Pause and Continue = True
'Can ShutDown = True
'Can Stop = True
'Status = Paused
'Status = Running
'Status = Stopped
'Status = Running
'4:14:49 PM - Custom command received: 128
'4:14:49 PM - Custom command received: 129
'ServiceController arg1
'ServiceController arg2
Comentários
Você pode usar a ServiceController classe para se conectar e controlar o comportamento dos serviços existentes.You can use the ServiceController class to connect to and control the behavior of existing services. Ao criar uma instância da ServiceController classe, você define suas propriedades para que ela interaja com um serviço do Windows específico.When you create an instance of the ServiceController class, you set its properties so it interacts with a specific Windows service. Em seguida, você pode usar a classe para iniciar, parar e, de outra forma, manipular o serviço.You can then use the class to start, stop, and otherwise manipulate the service.
Provavelmente, você usará o ServiceController componente em uma capacidade administrativa.You will most likely use the ServiceController component in an administrative capacity. Por exemplo, você pode criar um aplicativo Web ou do Windows que envia comandos personalizados para um serviço por meio da ServiceController instância do.For example, you could create a Windows or Web application that sends custom commands to a service through the ServiceController instance. Isso seria útil, pois o snap-in do console de gerenciamento Microsoft SCM (Service Control Manager) não oferece suporte a comandos personalizados.This would be useful, because the Service Control Manager (SCM) Microsoft Management Console snap-in does not support custom commands.
Depois de criar uma instância do ServiceController , você deve definir duas propriedades para identificar o serviço com o qual ele interage: o nome do computador e o nome do serviço que você deseja controlar.After you create an instance of ServiceController, you must set two properties on it to identify the service with which it interacts: the computer name and the name of the service you want to control.
Observação
Por padrão, MachineName o é definido como o computador local, portanto, você não precisa alterá-lo, a menos que queira definir a instância para apontar para outro computador.By default, MachineName is set to the local computer, so you do not need to change it unless you want to set the instance to point to another computer.
Em geral, o autor do serviço grava o código que personaliza a ação associada a um comando específico.Generally, the service author writes code that customizes the action associated with a specific command. Por exemplo, um serviço pode conter código para responder a um ServiceBase.OnPause comando.For example, a service can contain code to respond to an ServiceBase.OnPause command. Nesse caso, o processamento personalizado para a Pause tarefa é executado antes de o sistema pausar o serviço.In that case, the custom processing for the Pause task runs before the system pauses the service.
O conjunto de comandos que um serviço pode processar depende de suas propriedades; por exemplo, você pode definir a CanStop propriedade para um serviço como false .The set of commands a service can process depends on its properties; for example, you can set the CanStop property for a service to false. Essa configuração renderiza o Stop comando indisponível nesse serviço específico; ele impede que você interrompa o serviço do SCM desabilitando o botão necessário.This setting renders the Stop command unavailable on that particular service; it prevents you from stopping the service from the SCM by disabling the necessary button. Se você tentar interromper o serviço do seu código, o sistema gerará um erro e exibirá a mensagem de erro "falha ao parar servicename ".If you try to stop the service from your code, the system raises an error and displays the error message "Failed to stop servicename."
Construtores
| ServiceController() |
Inicializa uma nova instância da classe ServiceController que não está associada a um serviço específico.Initializes a new instance of the ServiceController class that is not associated with a specific service. |
| ServiceController(String) |
Inicializa uma nova instância da classe ServiceController que está associada a um serviço existente no computador local.Initializes a new instance of the ServiceController class that is associated with an existing service on the local computer. |
| ServiceController(String, String) |
Inicializa uma nova instância da classe ServiceController que está associada a um serviço existente no computador especificado.Initializes a new instance of the ServiceController class that is associated with an existing service on the specified computer. |
Propriedades
| CanPauseAndContinue |
Obtém um valor que indica se o serviço pode ser colocado em pausa e retomado.Gets a value indicating whether the service can be paused and resumed. |
| CanRaiseEvents |
Obtém um valor que indica se o componente pode acionar um evento.Gets a value indicating whether the component can raise an event. (Herdado de Component) |
| CanShutdown |
Obtém um valor que indica se o serviço deve ser notificado quando o sistema está sendo desligado.Gets a value indicating whether the service should be notified when the system is shutting down. |
| CanStop |
Obtém um valor que indica se o serviço pode ser interrompido depois de ser iniciado.Gets a value indicating whether the service can be stopped after it has started. |
| Container |
Obtém o IContainer que contém o Component.Gets the IContainer that contains the Component. (Herdado de Component) |
| DependentServices |
Obtém o conjunto de serviços que depende do serviço associado a essa instância de ServiceController.Gets the set of services that depends on the service associated with this ServiceController instance. |
| DesignMode |
Obtém um valor que indica se o Component está no modo de design no momento.Gets a value that indicates whether the Component is currently in design mode. (Herdado de Component) |
| DisplayName |
Obtém ou define um nome amigável para o serviço.Gets or sets a friendly name for the service. |
| Events |
Obtém a lista de manipuladores de eventos que estão anexados a este Component.Gets the list of event handlers that are attached to this Component. (Herdado de Component) |
| MachineName |
Obtém ou define o nome do computador no qual este serviço reside.Gets or sets the name of the computer on which this service resides. |
| ServiceHandle |
Obtém o identificador do serviço.Gets the handle for the service. |
| ServiceName |
Obtém ou define o nome que identifica o serviço ao qual essa instância faz referência.Gets or sets the name that identifies the service that this instance references. |
| ServicesDependedOn |
O conjunto de serviços que esse serviço depende.The set of services that this service depends on. |
| ServiceType |
Obtém o tipo de serviço que faz referência a esse objeto.Gets the type of service that this object references. |
| Site |
Obtém ou define o ISite do Component.Gets or sets the ISite of the Component. (Herdado de Component) |
| StartType |
Obtém um valor que indica como o serviço representado pelo objeto ServiceController é iniciado.Gets a value that indicates how the service represented by the ServiceController object starts. |
| Status |
Obtém o status do serviço que é referenciado por essa instância.Gets the status of the service that is referenced by this instance. |
Métodos
| Close() |
Desconecta esta instância ServiceController do serviço e libera todos os recursos alocados pela instância.Disconnects this ServiceController instance from the service and frees all the resources that the instance allocated. |
| Continue() |
Retoma um serviço depois de ele ter sido colocado em pausa.Continues a service after it has been paused. |
| CreateObjRef(Type) |
Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Herdado de MarshalByRefObject) |
| Dispose() |
Realiza tarefas definidas pelo aplicativo associadas à liberação ou à redefinição de recursos não gerenciados.Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. |
| Dispose() |
Libera todos os recursos usados pelo Component.Releases all resources used by the Component. (Herdado de Component) |
| Dispose(Boolean) |
Libera os recursos não gerenciados usados pelo ServiceController e opcionalmente libera os recursos gerenciados.Releases the unmanaged resources used by the ServiceController and optionally releases the managed resources. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| ExecuteCommand(Int32) |
Executa um comando personalizado no serviço.Executes a custom command on the service. |
| GetDevices() |
Recupera os serviços de driver de dispositivo no computador local.Retrieves the device driver services on the local computer. |
| GetDevices(String) |
Recupera os serviços de driver de dispositivo no computador especificado.Retrieves the device driver services on the specified computer. |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetLifetimeService() |
Obsoleto.
Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Herdado de MarshalByRefObject) |
| GetService(Type) |
Retorna um objeto que representa um serviço fornecido pelo Component ou pelo seu Container.Returns an object that represents a service provided by the Component or by its Container. (Herdado de Component) |
| GetServices() |
Recupera todos os serviços no computador local, exceto os serviços de driver de dispositivo.Retrieves all the services on the local computer, except for the device driver services. |
| GetServices(String) |
Recupera todos os serviços no computador especificado, exceto os serviços de driver de dispositivo.Retrieves all the services on the specified computer, except for the device driver services. |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| InitializeLifetimeService() |
Obsoleto.
Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.Obtains a lifetime service object to control the lifetime policy for this instance. (Herdado de MarshalByRefObject) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| MemberwiseClone(Boolean) |
Cria uma cópia superficial do objeto MarshalByRefObject atual.Creates a shallow copy of the current MarshalByRefObject object. (Herdado de MarshalByRefObject) |
| Pause() |
Suspende uma operação do serviço.Suspends a service's operation. |
| Refresh() |
Atualiza os valores de propriedade redefinindo as propriedades para seus valores atuais.Refreshes property values by resetting the properties to their current values. |
| Start() |
Inicia o serviço, não passando nenhum argumento.Starts the service, passing no arguments. |
| Start(String[]) |
Inicia um serviço, passando os argumentos especificados.Starts a service, passing the specified arguments. |
| Stop() |
Para este serviço e quaisquer serviços que dependam dele.Stops this service and any services that are dependent on this service. |
| ToString() |
Retorna um String que contém o nome do Component, se houver.Returns a String containing the name of the Component, if any. Esse método não deve ser substituído.This method should not be overridden. (Herdado de Component) |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
| WaitForStatus(ServiceControllerStatus) |
Aguarda infinitamente o serviço atingir o status especificado.Infinitely waits for the service to reach the specified status. |
| WaitForStatus(ServiceControllerStatus, TimeSpan) |
Espera o serviço atingir o status especificado ou o tempo limite especificado expirar.Waits for the service to reach the specified status or for the specified time-out to expire. |
Eventos
| Disposed |
Ocorre quando o componente é disposto por uma chamada ao método Dispose().Occurs when the component is disposed by a call to the Dispose() method. (Herdado de Component) |