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를 만들 수 있습니다 또는 사용자 지정 전송 하는 웹 애플리케이션 명령을 통해 해당 서비스에는 ServiceController 인스턴스. SCM(서비스 제어 관리자) Microsoft 관리 콘솔 스냅인은 사용자 지정 명령을 지원하지 않기 때문에 유용합니다.

인스턴스 ServiceController를 만든 후에는 두 가지 속성을 설정하여 상호 작용하는 서비스를 식별해야 합니다. 컴퓨터 이름과 제어하려는 서비스의 이름입니다.

참고

기본적으로 MachineName 로컬 컴퓨터로 설정되므로 인스턴스를 다른 컴퓨터를 가리키도록 설정하지 않는 한 변경할 필요가 없습니다.

일반적으로 서비스 작성자가 특정 명령과 연결된 작업을 사용자 지정하는 코드를 작성합니다. 예를 들어 서비스에 명령에 응답하는 코드가 ServiceBase.OnPause 포함될 수 있습니다. 이 경우 시스템에서 서비스를 일시 중지하기 전에 태스크에 Pause 대한 사용자 지정 처리가 실행됩니다.

서비스에서 처리할 수 있는 명령 집합은 해당 속성에 따라 달라집니다. 예를 들어 서비스의 false속성을 .로 설정할 CanStop 수 있습니다. 이 설정은 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

ComponentISite를 가져오거나 설정합니다.

(다음에서 상속됨 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)

적용 대상

추가 정보