首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 建立 Windows 服務完整教學:從專案建立到部署測試

     編輯:關於C語言

步驟 1:建立服務專案

Visual Studio → 新增專案 → Windows 服務(舊稱 NT 服務) → 命名專案(如 mcWinService)。

專案自動產生 Service1.cs(繼承 ServiceBase)。設定 ServiceName 屬性(或在建構子 this.ServiceName = "mcWinService"),便於識別。

步驟 2:實作服務邏輯

覆寫兩個核心方法:

protected override void OnStart(string[] args) {
    // 服務啟動時執行:寫入日誌、啟動執行緒、開啟連接埠等
    File.AppendAllText(@"C:\temp\service.log", "Service Started: " + DateTime.Now);
}

protected override void OnStop() {
    // 服務停止時執行:釋放資源、關閉連線、寫入日誌
    File.AppendAllText(@"C:\temp\service.log", "Service Stopped: " + DateTime.Now);
}

步驟 3:安裝與解除安裝

建置產生 mcWinService.exe。以系統管理員身分開啟「開發人員命令提示字元」:

REM 安裝
installutil C:\mcWinService\bin\Debug\mcWinService.exe

REM 解除安裝
installutil /u C:\mcWinService\bin\Debug\mcWinService.exe

installutil.exe 會讀取專案中的 ProjectInstaller 類別(含 ServiceProcessInstaller 與 ServiceInstaller),向 SCM 註冊服務。

步驟 4:啟動、停止與管理

  • 服務管理工具:services.msc 或「電腦管理」→「服務」
  • 尋找 mcWinService,右鍵可「啟動」、「停止」、「暫停」、「繼續」
  • 設定「啟動類型」:自動/手動/停用
  • 「復原」分頁設定失敗重啟策略

步驟 5:驗證測試

查看 C:\temp\service.log 確認啟動/停止記錄。實際專案中建議使用 EventLog 寫入 Windows 事件記錄檔,而非純文字檔。

進階主題

服務帳戶權限

ServiceProcessInstaller.Account 可設為:

  • LocalSystem:最高權限,無網路存取權
  • LocalService:低權限,匿名網路存取
  • NetworkService:低權限,電腦身分網路存取
  • User:指定使用者帳號(需密碼)

偵錯技巧

// 在 Program.cs Main 中加入條件編譯,支援直接以 Console 執行偵錯
#if DEBUG
    if (Environment.UserInteractive) {
        var svc = new mcWinService();
        svc.OnStart(null);
        Console.WriteLine("Press any key to stop...");
        Console.ReadKey();
        svc.OnStop();
        return;
    }
#endif
ServiceBase.Run(new mcWinService());

自訂命令

protected override void OnCustomCommand(int command) {
    // command 128-255 為使用者自訂
    if (command == 130) ReloadConfiguration();
}

透過 sc control mcWinService 130 觸發。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved