Windows 服務應用程式簡介Introduction to Windows Service Applications

Microsoft Windows 服務 (以前稱為 NT 服務) 讓您能夠建立長時間執行的應用程式,並使其在自己的 Windows 工作階段中執行。Microsoft Windows services, formerly known as NT services, enable you to create long-running executable applications that run in their own Windows sessions. 這些服務可以在電腦開機時自動啟動、可以暫停和重新啟動,而且不會顯示任何使用者介面。These services can be automatically started when the computer boots, can be paused and restarted, and do not show any user interface. 這些功能讓服務非常適合在伺服器上使用,或者,當您需要不會干擾其他在同一部電腦上工作的使用者且又長時間執行的功能時使用。These features make services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer. 您也可以在特定使用者帳戶的安全性內容中執行服務,此使用者帳戶不同於登入的使用者帳戶或預設電腦帳戶。You can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account. 如需服務和 Windows 工作階段的詳細資訊,請參閱 Windows SDK 文件。For more information about services and Windows sessions, see the Windows SDK documentation.

您可以藉由建立要安裝為服務的應用程式,輕鬆地建立服務。You can easily create services by creating an application that is installed as a service. 例如,假設您想要監視效能計數器資料並回應閾值。For example, suppose you want to monitor performance counter data and react to threshold values. 您可以撰寫 Windows 服務應用程式來接聽效能計數器資料、部署應用程式,然後開始收集和分析資料。You could write a Windows Service application that listens to the performance counter data, deploy the application, and begin collecting and analyzing data.

您會以 Microsoft Visual Studio 專案來建立服務,在其中定義程式碼來控制可以傳送到服務的命令,以及在收到命令時應該採取的動作。You create your service as a Microsoft Visual Studio project, defining code within it that controls what commands can be sent to the service and what actions should be taken when those commands are received. 可傳送到服務的命令包括啟動、暫停、繼續和停止服務;您也可以執行自訂命令。Commands that can be sent to a service include starting, pausing, resuming, and stopping the service; you can also execute custom commands.

當您建立和建置應用程式之後,可執行命令列公用程式 InstallUtil.exe,並傳入服務可執行檔的路徑來進行安裝。After you create and build the application, you can install it by running the command-line utility InstallUtil.exe and passing the path to the service's executable file. 您接著可以使用服務控制管理員來啟動、停止、暫停、繼續及設定服務。You can then use the Services Control Manager to start, stop, pause, resume, and configure your service. 您也可以在 [伺服器總管] 的 [服務] 節點中完成這其中許多相同的工作,或是使用 ServiceController 類別來完成。You can also accomplish many of these same tasks in the Services node in Server Explorer or by using the ServiceController class.

服務應用程式相較於其他 Visual Studio 應用程式Service Applications vs. Other Visual Studio Applications

服務應用程式的運作在某些方面有別於許多其他專案類型:Service applications function differently from many other project types in several ways:

  • 服務應用程式專案所建立的已編譯可執行檔必須先安裝在伺服器上,然後專案才能正常地運作。The compiled executable file that a service application project creates must be installed on the server before the project can function in a meaningful way. 您無法按 F5 鍵或 F11 鍵來偵錯或執行服務應用程式;您無法立即執行服務或逐步執行其程式碼。You cannot debug or run a service application by pressing F5 or F11; you cannot immediately run a service or step into its code. 反之,您必須安裝並啟動服務,然後將偵錯工具附加到服務的處理序。Instead, you must install and start your service, and then attach a debugger to the service's process. 如需詳細資訊,請參閱如何:偵錯 Windows 服務應用程式For more information, see How to: Debug Windows Service Applications.

  • 不同於某些類型的專案,您必須為服務應用程式建立安裝元件。Unlike some types of projects, you must create installation components for service applications. 安裝元件會在伺服器上安裝並註冊服務,以及使用 Windows 服務控制管理員來建立服務項目。The installation components install and register the service on the server and create an entry for your service with the Windows Services Control Manager. 如需詳細資訊,請參閱如何:將安裝程式新增至服務應用程式For more information, see How to: Add Installers to Your Service Application.

  • 服務應用程式的 Main 方法必須針對專案所包含的服務發出 Run 命令。The Main method for your service application must issue the Run command for the services your project contains. Run 方法會將服務載入到適當伺服器上的服務控制管理員The Run method loads the services into the Services Control Manager on the appropriate server. 如果您使用 Windows 服務專案範本,即會自動撰寫這個方法。If you use the Windows Services project template, this method is written for you automatically. 請注意,載入服務與啟動服務不同。Note that loading a service is not the same thing as starting the service. 如需詳細資訊,請參閱下方的「服務存留期」。See "Service Lifetime" below for more information.

  • Windows 服務應用程式執行所在的視窗工作站,不同於登入使用者的互動式工作站。Windows Service applications run in a different window station than the interactive station of the logged-on user. 視窗工作站是一個安全的物件,其中包含剪貼簿、一組通用元素,以及一個桌面物件群組。A window station is a secure object that contains a Clipboard, a set of global atoms, and a group of desktop objects. 由於 Windows 服務的工作站不是互動式工作站,因此看不到從 Windows 服務應用程式內引發的對話方塊,因而可能造成程式停止回應。Because the station of the Windows service is not an interactive station, dialog boxes raised from within a Windows service application will not be seen and may cause your program to stop responding. 同樣地,錯誤訊息應該記錄於 Windows 事件記錄檔中,而不應在使用者介面中引發。Similarly, error messages should be logged in the Windows event log rather than raised in the user interface.

    .NET Framework 所支援的 Windows 服務類別不支援與互動式工作站 (也就是登入的使用者) 進行互動。The Windows service classes supported by the .NET Framework do not support interaction with interactive stations, that is, the logged-on user. .NET Framework 也不會包含代表工作站和桌面的類別。The .NET Framework also does not include classes that represent stations and desktops. 如果您的 Windows 服務必須與其他工作站互動,您將需要存取非受控的 Windows API。If your Windows service must interact with other stations, you will need to access the unmanaged Windows API. 如需詳細資訊,請參閱 Windows SDK 文件。For more information, see the Windows SDK documentation.

    Windows 服務與使用者或其他工作站的互動必須經過精心設計以包含如下的案例:沒有登入的使用者,或者使用者具備一組未預期的桌面物件。The interaction of the Windows service with the user or other stations must be carefully designed to include scenarios such as there being no logged on user, or the user having an unexpected set of desktop objects. 在某些情況下,撰寫由使用者控制的 Windows 應用程式可能更為合適。In some cases, it may be more appropriate to write a Windows application that runs under the control of the user.

  • Windows 服務應用程式會在自己的安全性內容中執行,並在使用者登入安裝應用程式所在的 Windows 電腦之前便啟動。Windows service applications run in their own security context and are started before the user logs into the Windows computer on which they are installed. 您應該仔細規劃要在哪些使用者帳戶內執行服務;在系統帳戶下執行的服務,其權限會高於在使用者帳戶下執行的服務。You should plan carefully what user account to run the service within; a service running under the system account has more permissions and privileges than a user account.

服務存留期Service Lifetime

服務會在其存留期中會經歷數個內部狀態。A service goes through several internal states in its lifetime. 首先,服務會安裝於執行所在的系統上。First, the service is installed onto the system on which it will run. 此流程會針對服務專案執行安裝程式,並將服務載入該電腦的服務控制管理員This process executes the installers for the service project and loads the service into the Services Control Manager for that computer. 服務控制管理員是由 Windows 提供來管理服務的重要公用程式。The Services Control Manager is the central utility provided by Windows to administer services.

載入服務之後,必須加以啟動。After the service has been loaded, it must be started. 啟動服務即可讓它開始運作。Starting the service allows it to begin functioning. 啟動服務的方式有三種:從服務控制管理員、從伺服器總管,或從程式碼中呼叫 Start 方法。You can start a service from the Services Control Manager, from Server Explorer, or from code by calling the Start method. Start 方法會將處理傳遞到應用程式的 OnStart 方法,並處理您在該處定義的任何程式碼。The Start method passes processing to the application's OnStart method and processes any code you have defined there.

執行中的服務可以此狀態無限期存在,直到它停止或暫停,或是直到電腦關機為止。A running service can exist in this state indefinitely until it is either stopped or paused or until the computer shuts down. 服務可以下列三種基本狀態之一存在:RunningPausedStoppedA service can exist in one of three basic states: Running, Paused, or Stopped. 服務也可以報告擱置命令的狀態:ContinuePendingPausePendingStartPendingStopPendingThe service can also report the state of a pending command: ContinuePending, PausePending, StartPending, or StopPending. 這些狀態指出已發出命令 (例如要暫停執行中服務的命令),但尚未執行。These statuses indicate that a command has been issued, such as a command to pause a running service, but has not been carried out yet. 您可以查詢 Status 以判斷服務處於何種狀態,或者使用 WaitForStatus 在發生這其中任一種狀態時執行動作。You can query the Status to determine what state a service is in, or use the WaitForStatus to carry out an action when any of these states occurs.

暫停、停止或繼續執行服務的方式有三種:從服務控制管理員、從伺服器總管,或在程式碼中呼叫方法。You can pause, stop, or resume a service from the Services Control Manager, from Server Explorer, or by calling methods in code. 這其中的每個動作都可在服務中呼叫相關聯的程序 (OnStopOnPauseOnContinue),而您可以在其中定義要在服務變更狀態時所執行的額外處理。Each of these actions can call an associated procedure in the service (OnStop, OnPause, or OnContinue), in which you can define additional processing to be performed when the service changes state.

服務的類型Types of Services

在 Visual Studio 中,使用 .NET Framework 可建立兩種類型的服務。There are two types of services you can create in Visual Studio using the .NET Framework. 若服務是處理序中的唯一服務,即會為其指派 Win32OwnProcess 類型。Services that are the only service in a process are assigned the type Win32OwnProcess. 若服務會與其他服務共用處理序,則會為其指派 Win32ShareProcess 類型。Services that share a process with another service are assigned the type Win32ShareProcess. 您可以藉由查詢 ServiceType 屬性來擷取服務類型。You can retrieve the service type by querying the ServiceType property.

如果您查詢尚未在 Visual Studio 中建立的現有服務,則可能會看到其他服務類型。You might occasionally see other service types if you query existing services that were not created in Visual Studio. 如需詳細資訊,請參閱 ServiceTypeFor more information on these, see the ServiceType.

服務和 ServiceController 元件Services and the ServiceController Component

ServiceController 元件可用來連線到已安裝的服務並操控其狀態;使用 ServiceController 元件可啟動和停止服務、暫停和繼續其運作,以及將自訂命令傳送到服務。The ServiceController component is used to connect to an installed service and manipulate its state; using a ServiceController component, you can start and stop a service, pause and continue its functioning, and send custom commands to a service. 不過,當您建立服務應用程式時,不需要使用 ServiceController 元件。However, you do not need to use a ServiceController component when you create a service application. 事實上,在大部分情況下,ServiceController 元件所存在的應用程式,應該有別於定義服務的 Windows 服務應用程式。In fact, in most cases your ServiceController component should exist in a separate application from the Windows service application that defines your service.

如需詳細資訊,請參閱 ServiceControllerFor more information, see ServiceController.

需求Requirements

  • 服務必須建立於 Windows 服務應用程式專案或其他已啟用 .NET Framework 的專案中,以便在建置時建立 .exe 檔並繼承自 ServiceBase 類別。Services must be created in a Windows Service application project or another .NET Framework–enabled project that creates an .exe file when built and inherits from the ServiceBase class.

  • 包含 Windows 服務的專案必須具備專案及其服務的安裝元件。Projects containing Windows services must have installation components for the project and its services. 這可輕鬆地從 [屬性] 視窗來完成。This can be easily accomplished from the Properties window. 如需詳細資訊,請參閱如何:將安裝程式新增至服務應用程式For more information, see How to: Add Installers to Your Service Application.

另請參閱See also