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

C# 實作 Windows Service 建立、安裝與移除完整教學

     編輯:關於C#

建立專案

  1. Visual Studio → 新增專案 → Windows 服務(C#)。
  2. 專案包含 Service1.cs(設計介面)與 Program.cs(進入點)。

服務核心程式碼

using System; using System.ServiceProcess; using System.Threading; using System.Windows.Forms;

namespace CareEye {
    public partial class CareEye : ServiceBase {
        Thread _mainThread;
        public CareEye() {
            InitializeComponent();
            _mainThread = new Thread(ThreadFunc) { Priority = ThreadPriority.Lowest };
        }

        static void Main() {
            ServiceBase.Run(new CareEye());
        }

        protected override void OnStart(string[] args) {
            _mainThread.Start(); // 啟動背景執行緒
        }

        protected override void OnStop() {
            _mainThread.Abort(); // 停止執行緒
        }

        void ThreadFunc() {
            int lastHour = DateTime.Now.Hour;
            while (true) {
                Thread.Sleep(60000); // 每分鐘檢查
                if (DateTime.Now.Hour - 1 == lastHour) {
                    MessageBox.Show("為了愛護您的眼睛,請暫時休息5分鐘並向遠處眺望!",
                        "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning,
                        MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                    lastHour = DateTime.Now.Hour;
                }
            }
        }
    }
}

加入安裝程式

  1. 在 Service1.cs 設計介面右鍵 → 加入安裝程式。
  2. 產生 ProjectInstaller.cs,包含 serviceProcessInstaller1 與 serviceInstaller1。
  3. 設定屬性:
  • serviceProcessInstaller1.Account = LocalSystem(或 User/NetworkService)。
  • serviceInstaller1.Parent = serviceProcessInstaller1。
  • serviceInstaller1.ServiceName = 服務顯示名稱(如 "CareEye")。

建置與安裝

  1. 建置專案(Release 模式),取得 bin\Release\CareEye.exe。
  2. 複製至固定路徑(如 F:\CareEye.exe)。
  3. 開啟「Visual Studio 開發人員命令提示字元」(或直接進入 .NET Framework 目錄):
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319  (依安裝版本調整)
installutil F:\CareEye.exe          // 安裝服務
installutil /u F:\CareEye.exe       // 移除服務

啟動服務

  • 開啟 services.msc → 找到 "CareEye" → 右鍵 啟動。
  • 或命令列:net start CareEye / net stop CareEye。

重要注意事項

  • 服務執行於 Session 0,無法直接顯示 UI(MessageBox、Form)。範例中 MessageBox.Show 加上 MessageBoxOptions.DefaultDesktopOnly 僅供測試,正式環境請改用事件日誌(EventLog)記錄。
  • Thread.Abort() 不推薦用於生產環境,建議使用 CancellationToken 或旗標讓執行緒自行結束。
  • 安裝路徑不可包含中文或特殊符號,避免 installutil 失敗。
  • 服務名稱 (ServiceName) 需唯一,不可與現有服務重複。

進階:偵錯技巧

// 在 OnStart 加入
#if DEBUG
    System.Diagnostics.Debugger.Launch(); // 啟動時自動附加偵錯器
#endif

或將服務邏輯抽離為獨立類別,以 Console Application 執行測試,再移植回服務。

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