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

從零建立 Windows Service:Visual Studio 完整實作與偵錯指南

     編輯:關於C#

建立專案

  1. VS 選單:File → New → Project
  2. 篩選「Windows Service」範本(或「Worker Service」.NET Core/5+)
  3. 專案命名 TestService,確定
新增專案對話方塊

重命名與基本設定

  1. 方案總管右鍵 Service1.cs → Rename → MyFirstService.cs
  2. 雙擊進入設計檢視,屬性視窗修改 ServiceName = "MyFirstService"
  3. 從工具箱拖入 EventLog 元件,命名 eventLog1
  4. 設定 eventLog1.Log = "Application"、eventLog1.Source = "MyFirstService"

核心程式碼:OnStart / OnStop

using System.Diagnostics;
using System.ServiceProcess;

namespace TestService {
    public partial class MyFirstService : ServiceBase {
        public MyFirstService() => InitializeComponent();

        protected override void OnStart(string[] args) {
            eventLog1.WriteEntry("Service started at " + DateTime.Now);
            // TODO: 啟動背景工作執行緒、Timer、檔案監視器等
        }

        protected override void OnStop() {
            eventLog1.WriteEntry("Service stopped at " + DateTime.Now);
            // TODO: 釋放資源、停止執行緒、關閉連線
        }
    }
}

加入安裝程式

  1. 設計檢視右鍵 → Add Installer,產生 ProjectInstaller.cs
  2. 選取 serviceProcessInstaller1,設定 Account = LocalSystem
  3. 選取 serviceInstaller1,設定 StartType = Automatic(或 Manual)

安裝與解除安裝

開啟「Visual Studio 開發人員命令提示字元」(管理員):

cd 專案輸出目錄\bin\Debug
installutil TestService.exe          # 安裝
installutil /u TestService.exe       # 解除安裝

安裝後可在 services.msc 查看/啟動/停止服務。

事件檢視器顯示服務日誌

偵錯技巧:Attach to Process

  1. 建置專案
  2. 安裝服務(建議 StartType = Manual 方便開發)
  3. 在 services.msc 手動啟動服務
  4. VS 選單:Debug → Attach to Process
  5. 勾選「Show processes from all users」
  6. 選取服務進程(如 TestService.exe)→ Attach
  7. 下斷點、觀察變數、單步執行
Attach to Process 對話方塊
生產環境建議:
• 使用 EventLog 或 ILogger 記錄關鍵事件
• 長時間工作放在獨立執行緒/Task,OnStart 僅啟動、OnStop 通知取消
• 考慮改用 .NET Generic Host (IHostedService),支援依賴注入、設定檔、跨平台部署
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved