萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 撰寫 Windows Service 基礎流程完整教學

C# 開發 Windows 服務:從建立專案到安裝部署完整流程

.NET Framework 封裝好 SCM (Service Control Manager) 互動細節,開發者只需繼承 ServiceBase、實作生命週期事件、加入安裝類別,即可建立標準 Windows 服務。

步驟 1:建立專案與參考

  • 專案類型:Console Application 或 Windows Forms Application(輸出型別設為 Console Application)。
  • 加入參考:System.ServiceProcess.dll、System.Configuration.Install.dll。

步驟 2:實作服務類別

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);
        }
    }
}

步驟 3:進入點啟動服務

static class Program {
    static void Main() {
        ServiceBase.Run(new MyService());
    }
}

步驟 4:加入安裝類別 (Installer)

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);
    }
}

步驟 5:安裝/解除安裝/啟動/停止

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

步驟 6:開發用戶端管理工具 (選用)

服務無 UI,可另建 WinForms/WPF/ASP.NET Core 應用,透過:

  • ServiceController 類別:啟動/停止/暫停/查詢狀態。
  • WCF / Named Pipe / TCP / HTTP API:雙向通訊、傳遞指令與資料。
  • 事件日誌:EventLog 記錄關鍵資訊,管理工具讀取顯示。

常見坑與最佳實踐

  • OnStart 必須秒級返回:耗時工作務必丟到背景執行緒/Task,否則 SCM 判定逾時 (預設 30s) 會強制終止服務。
  • 例外處理:Worker 執行緒未捕獲例外會導致進程崩潰,使用 AppDomain.CurrentDomain.UnhandledException 記錄並嘗試重啟。
  • 權限最小化:非必要勿用 LocalSystem,改用專用服務帳戶 (Managed Service Account)。
  • 偵錯技巧:Debugger.Launch() 或將主邏輯抽離為 Library,用 Console App 參考除錯,再移回服務。
copyright © 萬盛學電腦網 all rights reserved