.NET Framework 封裝好 SCM (Service Control Manager) 互動細節,開發者只需繼承 ServiceBase、實作生命週期事件、加入安裝類別,即可建立標準 Windows 服務。
System.ServiceProcess.dll、System.Configuration.Install.dll。using System.ServiceProcess;
using System.Threading;
public class MyService : ServiceBase {
private Thread _workerThread;
private volatile bool _stopRequested;
public MyService() {
ServiceName = "MyCustomService";
CanPauseAndContinue = true;
CanShutdown = true;
AutoLog = true; // 自動寫入事件檢視器
}
protected override void OnStart(string[] args) {
_stopRequested = false;
_workerThread = new Thread(WorkerProc) { IsBackground = true };
_workerThread.Start();
}
protected override void OnStop() {
_stopRequested = true;
_workerThread.Join(TimeSpan.FromSeconds(10)); // 等待優雅結束
}
protected override void OnPause() {
// 暫停邏輯(如暫停處理佇列)
}
protected override void OnContinue() {
// 恢復邏輯
}
protected override void OnShutdown() {
OnStop(); // 系統關機時確保釋放資源
}
private void WorkerProc() {
while (!_stopRequested) {
// 實際業務邏輯:輪詢資料庫、處理訊息佇列、定時任務等
Thread.Sleep(1000);
}
}
}
static class Program {
static void Main() {
ServiceBase.Run(new MyService());
}
}
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
[RunInstaller(true)]
public class MyServiceInstaller : Installer {
public MyServiceInstaller() {
var processInstaller = new ServiceProcessInstaller {
Account = ServiceAccount.LocalSystem, // 或 User/NetworkService
Username = null,
Password = null
};
var serviceInstaller = new ServiceInstaller {
ServiceName = "MyCustomService",
DisplayName = "我的自訂服務",
Description = "示範 C# Windows Service 基礎架構",
StartType = ServiceStartMode.Automatic, // Manual/Disabled
ServicesDependedOn = new[] { "EventLog" } // 依賴服務
};
Installers.Add(processInstaller);
Installers.Add(serviceInstaller);
}
}
REM 管理員權限命令提示字元
cd /d "專案輸出目錄\bin\Release"
REM 安裝
InstallUtil.exe MyService.exe
REM 解除安裝
InstallUtil.exe /u MyService.exe
REM 啟動/停止 (或用 services.msc / sc 命令)
net start MyCustomService
net stop MyCustomService
服務無 UI,可另建 WinForms/WPF/ASP.NET Core 應用,透過:
ServiceController 類別:啟動/停止/暫停/查詢狀態。EventLog 記錄關鍵資訊,管理工具讀取顯示。AppDomain.CurrentDomain.UnhandledException 記錄並嘗試重啟。Debugger.Launch() 或將主邏輯抽離為 Library,用 Console App 參考除錯,再移回服務。