Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Visual Studio 建立 Windows 服務入門:從 Timer 到 InstallUtil 註冊全過程

編輯:Win7 系統基礎知識

為什麼用 Windows 服務?

  • 長時間背景工作(定時資料庫備份、同步)。
  • .NET Remoting / WCF 伺服器宿主,無需使用者登入即啟動。
  • 開機自動執行,不佔用桌面資源。

VS 建立服務專案步驟

  1. 「新增專案」→ 選「Windows Service」(Windows 服務)。
  2. 設計介面拖入 Timer 元件(來自「元件」而非「Windows Form」)。
  3. 設定 Timer.Interval(如 200ms = 秒 5 次)。
  4. 雙擊 Timer 進入 Tick 事件撰寫核心邏輯(如資料庫 Insert)。

加入安裝程式(關鍵)

  1. 設計檢視右鍵 →「加入安裝程式」,產生 ProjectInstaller.cs。
  2. 設定 serviceInstaller1:
    ServiceName = "MySampleService"
    StartType = Automatic(開機自動)。
  3. 設定 serviceProcessInstaller1:
    Account = LocalSystem(最高權限)。

編譯與註冊

  1. 建置專案(Release 模式),輸出至 bin\Release。
  2. 開啟「Visual Studio 命令提示字元」(或含 InstallUtil.exe 的路徑)。
  3. 執行:
    InstallUtil MyWindowsService.exe
  4. 成功會在 services.msc 看到服務,右鍵「啟動」即可運行。

常見坑點

  • Timer 必須用 System.Timers.Timer 或 System.Threading.Timer,非 WinForms Timer。
  • 資料庫連線字串勿寫死,建議放 app.config。
  • 例外處理:Tick 事件中捕獲例外並寫入事件日誌(EventLog),避免服務靜默掛掉。
  • 除錯技巧:在 OnStart 加 System.Diagnostics.Debugger.Launch() 附加偵錯器。

幾分鐘建立專屬背景服務,自動化維護任務輕鬆上手。

Copyright © Windows教程網 All Rights Reserved