ServiceController 类 
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
表示 Windows 服务并允许连接到正在运行或者已停止的服务、对其进行操作或获取有关它的信息。
public ref class ServiceController : System::ComponentModel::Componentpublic ref class ServiceController : IDisposablepublic class ServiceController : System.ComponentModel.Componentpublic class ServiceController : IDisposable[System.ServiceProcess.ServiceProcessDescription("ServiceControllerDesc")]
public class ServiceController : System.ComponentModel.Componenttype ServiceController = class
    inherit Componenttype ServiceController = class
    interface IDisposable[<System.ServiceProcess.ServiceProcessDescription("ServiceControllerDesc")>]
type ServiceController = class
    inherit ComponentPublic Class ServiceController
Inherits ComponentPublic Class ServiceController
Implements IDisposable- 继承
- 继承
- 
				ServiceController
- 属性
- 实现
示例
以下示例演示如何使用 ServiceController 类来控制 SimpleService 服务示例。
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 类连接到现有服务并控制其行为。 创建 类的 ServiceController 实例时,可以设置其属性,以便它与特定的 Windows 服务交互。 然后,可以使用 类启动、停止和以其他方式操作服务。
最有可能在 ServiceController 管理容量中使用 组件。 例如,可以创建一个 Windows 或 Web 应用程序,用于通过 ServiceController 实例将自定义命令发送到服务。 这将很有用,因为服务控制管理器 (SCM) Microsoft管理控制台管理单元不支持自定义命令。
创建 实例 ServiceController后,必须对其设置两个属性,以标识它与之交互的服务:计算机名称和要控制的服务的名称。
注意
默认情况下, MachineName 设置为本地计算机,因此无需更改它,除非要将实例设置为指向另一台计算机。
通常,服务作者会编写代码来自定义与特定命令关联的操作。 例如,服务可以包含用于响应命令的代码 ServiceBase.OnPause 。 在这种情况下,任务自定义处理 Pause 在系统暂停服务之前运行。
服务可以处理的命令集取决于其属性;例如,可以将服务的 属性设置为 CanStopfalse。 此设置使 Stop 命令在该特定服务上不可用;它禁止通过禁用必要的按钮从 SCM 停止服务。 如果尝试从代码中停止服务,系统会引发错误并显示错误消息“无法停止 servicename。
构造函数
| ServiceController() | 初始化与特定服务不关联的 ServiceController 类的新实例。 | 
| ServiceController(String) | 初始化与本地计算机上的现有服务关联的 ServiceController 类的新实例。 | 
| ServiceController(String, String) | 初始化与指定计算机上的现有服务关联的 ServiceController 类的新实例。 | 
属性
| CanPauseAndContinue | 获取一个值,该值指示是否可以暂停和继续服务。 | 
| CanRaiseEvents | 获取一个指示组件是否可以引发事件的值。(继承自 Component) | 
| CanShutdown | 获取一个值,该值指示在系统关闭时是否应通知服务。 | 
| CanStop | 获取一个值,该值指示服务在启动后是否可以停止。 | 
| Container | 获取包含 IContainer 的 Component。(继承自 Component) | 
| DependentServices | 获取依赖于与此 ServiceController 实例关联的服务的服务集。 | 
| DesignMode | 获取一个值,用以指示 Component 当前是否处于设计模式。(继承自 Component) | 
| DisplayName | 获取或设置服务的友好名称。 | 
| Events | 获取附加到此 Component 的事件处理程序的列表。(继承自 Component) | 
| MachineName | 获取或设置此服务所驻留的计算机的名称。 | 
| ServiceHandle | 获取服务的句柄。 | 
| ServiceName | 获取或设置对此实例引用的服务进行标识的名称。 | 
| ServicesDependedOn | 此服务所依赖的服务集。 | 
| ServiceType | 获取此对象引用的服务类型。 | 
| Site | (继承自 Component) | 
| StartType | 获取一个值,该值指示 ServiceController 对象表示的服务是如何启动的。 | 
| Status | 获取由此实例引用的服务的状态。 | 
方法
| Close() | 断开此 ServiceController 实例与服务的连接,并释放此实例分配的所有资源。 | 
| Continue() | 在服务暂停后继续该服务。 | 
| CreateObjRef(Type) | 创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。(继承自 MarshalByRefObject) | 
| Dispose() | 执行与释放或重置非托管资源关联的应用程序定义的任务。 | 
| Dispose() | 释放由 Component 使用的所有资源。(继承自 Component) | 
| Dispose(Boolean) | 释放由 ServiceController 占用的非托管资源,还可以另外再释放托管资源。 | 
| Equals(Object) | 确定指定对象是否等于当前对象。(继承自 Object) | 
| ExecuteCommand(Int32) | 对服务执行自定义命令。 | 
| GetDevices() | 检索本地计算机上的设备驱动程序服务。 | 
| GetDevices(String) | 检索指定计算机上的设备驱动程序服务。 | 
| GetHashCode() | 作为默认哈希函数。(继承自 Object) | 
| GetLifetimeService() | 
		已过时.
	 检索控制此实例的生存期策略的当前生存期服务对象。(继承自 MarshalByRefObject) | 
| GetService(Type) | 返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。(继承自 Component) | 
| GetServices() | 检索本地计算机上的所有服务(设备驱动程序服务除外)。 | 
| GetServices(String) | 检索指定计算机上的所有服务(设备驱动程序服务除外)。 | 
| GetType() | 获取当前实例的 Type。(继承自 Object) | 
| InitializeLifetimeService() | 
		已过时.
	 获取生存期服务对象来控制此实例的生存期策略。(继承自 MarshalByRefObject) | 
| MemberwiseClone() | 创建当前 Object 的浅表副本。(继承自 Object) | 
| MemberwiseClone(Boolean) | 创建当前 MarshalByRefObject 对象的浅表副本。(继承自 MarshalByRefObject) | 
| Pause() | 挂起服务的操作。 | 
| Refresh() | 通过将属性重置为其当前值来刷新属性值。 | 
| Start() | 启动服务,不传递任何自变量。 | 
| Start(String[]) | 启动服务,传递指定的参数。 | 
| Stop() | 停止该服务以及任何依赖于该服务的服务。 | 
| Stop(Boolean) | 停止服务以及依赖于此服务的任何服务(可选)。 | 
| ToString() | 返回包含 Component 的名称的 String(如果有)。 不应重写此方法。(继承自 Component) | 
| ToString() | 返回表示当前对象的字符串。(继承自 Object) | 
| WaitForStatus(ServiceControllerStatus) | 无休止的等待服务达到指定状态。 | 
| WaitForStatus(ServiceControllerStatus, TimeSpan) | 等待服务达到指定状态或等待指定的超时过期。 | 
事件
| Disposed | 在通过调用 Dispose() 方法释放组件时发生。(继承自 Component) |