ServiceController ServiceController ServiceController ServiceController Class

Definition

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
Inheritance
Attributes

Examples

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
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 'Main 
End Class 'Program
' 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

Remarks

You can use the ServiceController class to connect to and control the behavior of existing services. 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.

You will most likely use the ServiceController component in an administrative capacity. For example, you could create a Windows or Web application that sends custom commands to a service through the ServiceController instance. This would be useful, because the Service Control Manager (SCM) Microsoft Management Console snap-in does not support custom commands.

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.

Note

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. For example, a service can contain code to respond to an ServiceBase.OnPause command. In that case, the custom processing for the Pause task runs before the system pauses the service.

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. 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. If you try to stop the service from your code, the system raises an error and displays the error message "Failed to stop servicename."

Constructors

ServiceController() ServiceController() ServiceController() ServiceController()

Initializes a new instance of the ServiceController class that is not associated with a specific service.

ServiceController(String) ServiceController(String) ServiceController(String) ServiceController(String)

Initializes a new instance of the ServiceController class that is associated with an existing service on the local computer.

ServiceController(String, String) ServiceController(String, String) ServiceController(String, String) ServiceController(String, String)

Initializes a new instance of the ServiceController class that is associated with an existing service on the specified computer.

Properties

CanPauseAndContinue CanPauseAndContinue CanPauseAndContinue CanPauseAndContinue

Gets a value indicating whether the service can be paused and resumed.

CanRaiseEvents CanRaiseEvents CanRaiseEvents CanRaiseEvents

Gets a value indicating whether the component can raise an event.

(Inherited from Component)
CanShutdown CanShutdown CanShutdown CanShutdown

Gets a value indicating whether the service should be notified when the system is shutting down.

CanStop CanStop CanStop CanStop

Gets a value indicating whether the service can be stopped after it has started.

Container Container Container Container

Gets the IContainer that contains the Component.

(Inherited from Component)
DependentServices DependentServices DependentServices DependentServices

Gets the set of services that depends on the service associated with this ServiceController instance.

DesignMode DesignMode DesignMode DesignMode

Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
DisplayName DisplayName DisplayName DisplayName

Gets or sets a friendly name for the service.

Events Events Events Events

Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
MachineName MachineName MachineName MachineName

Gets or sets the name of the computer on which this service resides.

ServiceHandle ServiceHandle ServiceHandle ServiceHandle

Gets the handle for the service.

ServiceName ServiceName ServiceName ServiceName

Gets or sets the name that identifies the service that this instance references.

ServicesDependedOn ServicesDependedOn ServicesDependedOn ServicesDependedOn

The set of services that this service depends on.

ServiceType ServiceType ServiceType ServiceType

Gets the type of service that this object references.

Site Site Site Site

Gets or sets the ISite of the Component.

(Inherited from Component)
StartType StartType StartType StartType

Gets a value that indicates how the service represented by the ServiceController object starts.

Status Status Status Status

Gets the status of the service that is referenced by this instance.

Methods

Close() Close() Close() Close()

Disconnects this ServiceController instance from the service and frees all the resources that the instance allocated.

Continue() Continue() Continue() Continue()

Continues a service after it has been paused.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose() Dispose() Dispose() Dispose()
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Releases the unmanaged resources used by the ServiceController and optionally releases the managed resources.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
ExecuteCommand(Int32) ExecuteCommand(Int32) ExecuteCommand(Int32) ExecuteCommand(Int32)

Executes a custom command on the service.

GetDevices() GetDevices() GetDevices() GetDevices()

Retrieves the device driver services on the local computer.

GetDevices(String) GetDevices(String) GetDevices(String) GetDevices(String)

Retrieves the device driver services on the specified computer.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type) GetService(Type) GetService(Type) GetService(Type)

Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetServices() GetServices() GetServices() GetServices()

Retrieves all the services on the local computer, except for the device driver services.

GetServices(String) GetServices(String) GetServices(String) GetServices(String)

Retrieves all the services on the specified computer, except for the device driver services.

GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Pause() Pause() Pause() Pause()

Suspends a service's operation.

Refresh() Refresh() Refresh() Refresh()

Refreshes property values by resetting the properties to their current values.

Start() Start() Start() Start()

Starts the service, passing no arguments.

Start(String[]) Start(String[]) Start(String[]) Start(String[])

Starts a service, passing the specified arguments.

Stop() Stop() Stop() Stop()

Stops this service and any services that are dependent on this service.

ToString() ToString() ToString() ToString()

Returns a String containing the name of the Component, if any. This method should not be overridden.

(Inherited from Component)
WaitForStatus(ServiceControllerStatus) WaitForStatus(ServiceControllerStatus) WaitForStatus(ServiceControllerStatus) WaitForStatus(ServiceControllerStatus)

Infinitely waits for the service to reach the specified status.

WaitForStatus(ServiceControllerStatus, TimeSpan) WaitForStatus(ServiceControllerStatus, TimeSpan) WaitForStatus(ServiceControllerStatus, TimeSpan) WaitForStatus(ServiceControllerStatus, TimeSpan)

Waits for the service to reach the specified status or for the specified time-out to expire.

Events

Disposed Disposed Disposed Disposed

Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)

Applies to

See Also