Debug Windows Service


Debug Windows Service

> 前言

當完成一支 Windows Service 時,總是習慣性按下 F5 執行 Debug,將看見「Windows 服務啟動錯誤」的提示視窗
Windows 服務啟動錯誤
此時才會換成實際掛起服務,觀看 Error Log 來 Debug,說實在這方法真的累,後來看到同事的文章 Windows Service in Debug Mode 才知道原來有這麼簡單的方法就可以使 Windows Service 執行 Debug;也發現其實微軟官網有提供參考文件 Microsoft Docs - Windows 服務當做主控台應用程式來執行

> 執行環境

  • OS : Windows 10
  • IDE : Visual Studio 2019
  • .NET Framework 4.7.2

> 實作 Windows 服務當做主控台應用程式來執行

此方法概念很簡單,將 Windows Service 直接使用主控台應用程式的方式執行 Debug,讓開發者可以爽快的按下 F5 執行 Debug。當然別忘記 Commit 程式碼時,將調整過的設定都還原才可以喔!以下將逐步操作

> > Step1

建置一個 Windows Server 的專案 (範例專案名為 TestDebugService,Service1.cs 改名為 TestService.cs )
建置 Windows 服務專案

> > Step2

於 Program.cs 檔中將 Main 方法改為以下程式

//  判斷是否為使用者互動模式
if (Environment.UserInteractive == true)
{
        // 宣告並建立服務類別的執行個體
        TestService service = new TestService();

        service.Start();
        Console.WriteLine("服務開始");

        Console.WriteLine("按下任意鍵,結束服務");
        // 利用 ReadKey 將整個程式停在此處,使得程式可以持續執行
        Console.ReadKey();

        service.Stop();
        Console.WriteLine("服務結束");
}
else
{
        // 原本 Windows Service 建置時,Main 方法內的程式碼
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new TestService()
        };
        ServiceBase.Run(ServicesToRun);
}

程式碼說明:

  • Environment.UserInteractive : 此屬性為判斷處理程序是否為使用者互動模式。若為使用者互動模式 ( 有 UI 介面可操作,e.g. Console ) 則為 true,反之則為 false ( 無 UI 介面,e.g. 掛起服務 Run )
  • service.Start() : 此方法用來呼叫 TestService 內部的 OnStart 方法,因 OnStart 為受保護 ( protected ) 的方法,且又需要按照與 Windows Service 的進入點一樣執行程式,才多建立一個公開 ( public ) 方法供外部呼叫用

> > Step3

於 TestService.cs 檔中,建立 public 的 Start 方法,並貼上以下的程式碼

public void Start()
{
        this.OnStart(null);
}

> > Step4

於「方案總管」 > 「TestDebugService」 > 「右鍵」 > 「屬性」,將輸出類型調整為「主控台應用程式」
專案屬性位置
專案屬性

> > Step5

開心的按下 F5 來執行 Debug,記得下中斷點來看喔!
Windows Service Debug

> 心得

此方法幫助許多開發者可以爽快地按下 F5 執行,但這樣的測試其實算是比較後半段的階段,在這之前應該先做好單元測試 (Unit Testing)才是比較好的開發流程;之後要來多多磨練一下「單元測試」啦!!!

> Reference

#Debug Service #Windows Service #Debug Windows Service






你可能感興趣的文章

如何用 TensorFlow object detection API 的 Single Shot MultiBox Detector 來做 hand detection

如何用 TensorFlow object detection API 的 Single Shot MultiBox Detector 來做 hand detection

Chapter 5&6 重點功能&追蹤技術快速導覽

Chapter 5&6 重點功能&追蹤技術快速導覽

[21] 強制轉型 - ToNumber、ToPrimitive、StringNumericLiteral、NonDecimalIntegerLiteral

[21] 強制轉型 - ToNumber、ToPrimitive、StringNumericLiteral、NonDecimalIntegerLiteral






留言討論