ServiceController 类

定义

表示 Windows 服务并允许连接到正在运行或者已停止的服务、对其进行操作或获取有关它的信息。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
继承
ServiceController
继承
ServiceController
属性
实现

示例

下面的示例演示如何使用 ServiceController 类来控制 SimpleService 服务示例。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

注解

您可以使用 ServiceController 类来连接和控制现有服务的行为。You can use the ServiceController class to connect to and control the behavior of existing services. 创建类的实例时 ServiceController ,将设置其属性,使其与特定的 Windows 服务交互。When you create an instance of the ServiceController class, you set its properties so it interacts with a specific Windows service. 然后,可以使用类来启动、停止和以其他方式处理服务。You can then use the class to start, stop, and otherwise manipulate the service.

您很可能会 ServiceController 在管理容量中使用该组件。You will most likely use the ServiceController component in an administrative capacity. 例如,可以创建一个 Windows 或 Web 应用程序,用于通过实例将自定义命令发送到服务 ServiceControllerFor example, you could create a Windows or Web application that sends custom commands to a service through the ServiceController instance. 这会很有用,因为服务控制管理器 (SCM) Microsoft 管理控制台管理单元不支持自定义命令。This would be useful, because the Service Control Manager (SCM) Microsoft Management Console snap-in does not support custom commands.

创建实例后 ServiceController ,必须在其上设置两个属性以标识与其交互的服务:计算机名称和要控制的服务的名称。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.

备注

默认情况下, MachineName 设置为本地计算机,因此除非要将实例设置为指向另一台计算机,否则不需要更改它。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.

通常,服务作者编写代码,以自定义与特定命令相关联的操作。Generally, the service author writes code that customizes the action associated with a specific command. 例如,服务可以包含响应命令的代码 ServiceBase.OnPauseFor example, a service can contain code to respond to an ServiceBase.OnPause command. 在这种情况下,任务的自定义处理在 Pause 系统暂停服务之前运行。In that case, the custom processing for the Pause task runs before the system pauses the service.

服务可以处理的命令集取决于其属性;例如,可以将 CanStop 服务的属性设置为 falseThe set of commands a service can process depends on its properties; for example, you can set the CanStop property for a service to false. 此设置将使 Stop 命令在该特定服务上不可用; 它会阻止你通过禁用必要的按钮从 SCM 停止该服务。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. 如果尝试从代码中停止服务,系统会引发错误并显示错误消息 "无法停止" servicenameIf you try to stop the service from your code, the system raises an error and displays the error message "Failed to stop servicename."

构造函数

ServiceController()

初始化与特定服务不关联的 ServiceController 类的新实例。Initializes a new instance of the ServiceController class that is not associated with a specific service.

ServiceController(String)

初始化与本地计算机上的现有服务关联的 ServiceController 类的新实例。Initializes a new instance of the ServiceController class that is associated with an existing service on the local computer.

ServiceController(String, String)

初始化与指定计算机上的现有服务关联的 ServiceController 类的新实例。Initializes a new instance of the ServiceController class that is associated with an existing service on the specified computer.

属性

CanPauseAndContinue

获取一个值,该值指示是否可以暂停和继续服务。Gets a value indicating whether the service can be paused and resumed.

CanRaiseEvents

获取一个指示组件是否可以引发事件的值。Gets a value indicating whether the component can raise an event.

(继承自 Component)
CanShutdown

获取一个值,该值指示在系统关闭时是否应通知服务。Gets a value indicating whether the service should be notified when the system is shutting down.

CanStop

获取一个值,该值指示服务在启动后是否可以停止。Gets a value indicating whether the service can be stopped after it has started.

Container

获取包含 IContainerComponentGets the IContainer that contains the Component.

(继承自 Component)
DependentServices

获取依赖于与此 ServiceController 实例关联的服务的服务集。Gets the set of services that depends on the service associated with this ServiceController instance.

DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。Gets a value that indicates whether the Component is currently in design mode.

(继承自 Component)
DisplayName

获取或设置服务的友好名称。Gets or sets a friendly name for the service.

Events

获取附加到此 Component 的事件处理程序的列表。Gets the list of event handlers that are attached to this Component.

(继承自 Component)
MachineName

获取或设置此服务所驻留的计算机的名称。Gets or sets the name of the computer on which this service resides.

ServiceHandle

获取服务的句柄。Gets the handle for the service.

ServiceName

获取或设置对此实例引用的服务进行标识的名称。Gets or sets the name that identifies the service that this instance references.

ServicesDependedOn

此服务所依赖的服务集。The set of services that this service depends on.

ServiceType

获取此对象引用的服务类型。Gets the type of service that this object references.

Site

获取或设置 ComponentISiteGets or sets the ISite of the Component.

(继承自 Component)
StartType

获取一个值,该值指示 ServiceController 对象表示的服务是如何启动的。Gets a value that indicates how the service represented by the ServiceController object starts.

Status

获取由此实例引用的服务的状态。Gets the status of the service that is referenced by this instance.

方法

Close()

断开此 ServiceController 实例与服务的连接,并释放此实例分配的所有资源。Disconnects this ServiceController instance from the service and frees all the resources that the instance allocated.

Continue()

在服务暂停后继续该服务。Continues a service after it has been paused.

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(继承自 MarshalByRefObject)
Dispose()

执行与释放或重置非托管资源关联的应用程序定义的任务。Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

Dispose()

释放由 Component 使用的所有资源。Releases all resources used by the Component.

(继承自 Component)
Dispose(Boolean)

释放由 ServiceController 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the ServiceController and optionally releases the managed resources.

Equals(Object)

确定指定对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
ExecuteCommand(Int32)

对服务执行自定义命令。Executes a custom command on the service.

GetDevices()

检索本地计算机上的设备驱动程序服务。Retrieves the device driver services on the local computer.

GetDevices(String)

检索指定计算机上的设备驱动程序服务。Retrieves the device driver services on the specified computer.

GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetLifetimeService()
已过时。

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。Returns an object that represents a service provided by the Component or by its Container.

(继承自 Component)
GetServices()

检索本地计算机上的所有服务(设备驱动程序服务除外)。Retrieves all the services on the local computer, except for the device driver services.

GetServices(String)

检索指定计算机上的所有服务(设备驱动程序服务除外)。Retrieves all the services on the specified computer, except for the device driver services.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
InitializeLifetimeService()
已过时。

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(继承自 MarshalByRefObject)
Pause()

挂起服务的操作。Suspends a service's operation.

Refresh()

通过将属性重置为其当前值来刷新属性值。Refreshes property values by resetting the properties to their current values.

Start()

启动服务,不传递任何自变量。Starts the service, passing no arguments.

Start(String[])

启动服务,传递指定的参数。Starts a service, passing the specified arguments.

Stop()

停止该服务以及任何依赖于该服务的服务。Stops this service and any services that are dependent on this service.

ToString()

返回包含 Component 的名称的 String(如果有)。Returns a String containing the name of the Component, if any. 不应重写此方法。This method should not be overridden.

(继承自 Component)
ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)
WaitForStatus(ServiceControllerStatus)

无休止的等待服务达到指定状态。Infinitely waits for the service to reach the specified status.

WaitForStatus(ServiceControllerStatus, TimeSpan)

等待服务达到指定状态或等待指定的超时过期。Waits for the service to reach the specified status or for the specified time-out to expire.

事件

Disposed

在通过调用 Dispose() 方法释放组件时发生。Occurs when the component is disposed by a call to the Dispose() method.

(继承自 Component)

适用于

另请参阅