ServiceController 類別

定義

表示 Windows 服務,可以讓您連接到執行中或已停止的服務進行管理,或取得關於服務的資訊。

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 服務範例。

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 Management Console 嵌入式管理單元不支援自訂命令。

建立 的 ServiceController 實例之後,您必須在它上設定兩個屬性,以識別與其互動的服務:您要控制的電腦名稱稱和服務名稱。

注意

根據預設, MachineName 會設定為本機電腦,因此除非您要將 實例設定為指向另一部電腦,否則您不需要變更它。

一般而言,服務作者會撰寫程式碼,以自訂與特定命令相關聯的動作。 例如,服務可以包含回應命令的程式 ServiceBase.OnPause 代碼。 在此情況下,工作的 Pause 自訂處理會在系統暫停服務之前執行。

服務可以處理的一組命令取決於其屬性;例如,您可以將服務的 屬性設定 CanStopfalse 。 此設定會 Stop 轉譯該特定服務上無法使用的命令;它會停用必要的按鈕,以防止您停止 SCM 的服務。 如果您嘗試停止程式碼中的服務,系統會引發錯誤,並顯示錯誤訊息「無法停止 servicename 」。

建構函式

ServiceController()

初始化 ServiceController 類別的新執行個體,這個執行個體未與特定服務相關聯。

ServiceController(String)

初始化 ServiceController 類別的新執行個體,這個執行個體與本機電腦上現有的服務相關聯。

ServiceController(String, String)

初始化 ServiceController 類別的新執行個體,這個執行個體與指定電腦上現有的服務相關聯。

屬性

CanPauseAndContinue

取得值,表示服務是否可以暫停和繼續。

CanRaiseEvents

取得值,指出元件是否能引發事件。

(繼承來源 Component)
CanShutdown

取得值,表示當系統關閉時是否應該通知服務。

CanStop

取得值,表示服務啟動後是否可以停止。

Container

取得包含 IContainerComponent

(繼承來源 Component)
DependentServices

取得服務集,此服務集依賴與這個 ServiceController 執行個體關聯的服務。

DesignMode

取得值,指出 Component 目前是否處於設計模式。

(繼承來源 Component)
DisplayName

取得或設定服務的易記名稱。

Events

取得附加在這個 Component 上的事件處理常式清單。

(繼承來源 Component)
MachineName

取得或設定這項服務所在的電腦名稱。

ServiceHandle

取得服務的控制代碼。

ServiceName

取得或設定名稱,識別這個執行個體所參考的服務。

ServicesDependedOn

這項服務依賴的服務集。

ServiceType

取得這個物件所參考的服務類型。

Site

取得或設定 ComponentISite

(繼承來源 Component)
StartType

取得值,表示 ServiceController 物件所表示的服務如何開始。

Status

取得這個執行個體所參考之服務的狀態。

方法

Close()

從服務中斷連接這個 ServiceController 執行個體,並且釋放這個執行個體配置的所有資源。

Continue()

在服務暫停後繼續進行。

CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。

(繼承來源 MarshalByRefObject)
Dispose()

執行與釋放 (Free)、釋放 (Release) 或重設 Unmanaged 資源相關聯之應用程式定義的工作。

Dispose()

釋放 Component 所使用的所有資源。

(繼承來源 Component)
Dispose(Boolean)

釋放 ServiceController 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
ExecuteCommand(Int32)

在服務上執行自訂命令。

GetDevices()

擷取本機電腦上的裝置驅動程式服務。

GetDevices(String)

擷取指定電腦上的裝置驅動程式服務。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetLifetimeService()
已淘汰.

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。

(繼承來源 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)

適用於

另請參閱