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
[System.ServiceProcess.ServiceProcessDescription("ServiceControllerDesc")]
public class ServiceController : System.ComponentModel.Component
type ServiceController = class
    inherit Component
Public Class ServiceController
Inherits Component
繼承
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 應用程式,以透過ServiceController實例將自訂命令傳送至服務。For example, you could create a Windows or Web application that sends custom commands to a service through the ServiceController instance. 這項功能很有用,因為服務控制管理員(SCM) Microsoft Management Console 嵌入式管理單元不支援自訂命令。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.OnPause代碼來回應命令。For 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. 如果您嘗試從程式碼停止服務,系統會引發錯誤,並顯示錯誤訊息「無法停止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."

建構函式

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)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(繼承來源 MarshalByRefObject)
Dispose()
Dispose(Boolean)

釋放 ServiceController 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。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()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。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 的淺層複本 (Shallow Copy)。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 名稱的 StringReturns a String containing the name of the Component, if any. 不應覆寫此方法。This method should not be overridden.

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

適用於

另請參閱