Windows服務調試小結(附Demo)

本文版權歸mephisto和博客園共有,歡迎轉載,但須保留此段聲明,並給出原文連接,謝謝合做。app

閱讀目錄

本文版權歸mephisto和博客園共有,歡迎轉載,但須保留此段聲明,並給出原文連接,謝謝合做。ide

 

介紹

  有時候不可避免的要建些Windows服務。既然寫代碼,就須要調試,因爲這個東西搞的人很少,每一個人調試的方法也不全,因此在下在這裏小結一下調試方法。ui

搭建環境

一:建立一個Window Service

  文件->新建項目->Windows 服務。this

  而後咱們直接運行試試,而後提示以下:spa

  好吧,咱們就依他的意思,加個服務安裝程序和些相關的引用及其餘,結果以下:debug

  

  這樣咱們的環境就基本搭建好了,而後就是服務的安裝,運行bin\Debug\Install\install.bat便可。3d

調試方式

一:普通調試

  msdn上指出「必須從服務控制管理器的上下文中而不是 Visual Studio 中運行服務。 所以,調試服務不像調試其餘 Visual Studio 應用程序類型同樣簡單。 要調試服務,必須啓動該服務,而後將調試器附加到該服務正在其中運行的進程中。 而後你可使用全部 Visual Studio 的標準調試功能來調試你的應用程序」。調試

  因此咱們啓動服務,而後經過vs附件該服務進程,而後就能夠調試了。以下:code

 

二:特殊調試

  若是咱們不想建立服務就想調試代碼,其實能夠採用其餘的替代方式進行,只不過要改代碼。blog

  咱們找到程序的入口:Program.cs。

  原代碼以下:

 1     static class Program
 2     {
 3         /// <summary>
 4         /// 應用程序的主入口點。
 5         /// </summary>
 6         static void Main()
 7         {
 8             ServiceBase[] ServicesToRun;
 9             ServicesToRun = new ServiceBase[] 
10             { 
11                 new ServiceDebug() 
12             };
13             ServiceBase.Run(ServicesToRun);
14         }
15     }

  修改後代碼以下:

 1         protected override void OnStart(string[] args)
 2         {
 3             Timer timer = new Timer();
 4             timer.Interval = 1000;
 5             timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
 6             timer.Start();
 7 
 8         }
 9 
10         private void timer_Elapsed(object sender, ElapsedEventArgs e)
11         {
12 
13         }
14 
15         protected override void OnStop()
16         {
17         }
18 
19         public void Test(string[] args)
20         {
21             OnStart(args);
22         }
 1     static class Program
 2     {
 3         /// <summary>
 4         /// 應用程序的主入口點。
 5         /// </summary>
 6         static void Main()
 7         {
 8             ServiceDebug service = new ServiceDebug();
 9             service.Test(null);
10 
11             while (true)
12             {
13                 System.Threading.Thread.Sleep(1000);
14             }
15             return;
16 
17             ServiceBase[] ServicesToRun;
18             ServicesToRun = new ServiceBase[] 
19             { 
20                 new ServiceDebug() 
21             };
22             ServiceBase.Run(ServicesToRun);
23         }
24     }

  這樣,咱們就能夠進行調試了。

二:OnStart常規調試

  有時候咱們想正常的調試Onstart方法,可是,啓動服務後這個方法已經運行了,那麼咱們應該怎麼調試捏。

  咱們能夠在Onstart方法體前面加個Debugger.Launch();就能夠很愉快的調試了。以下:

 1         protected override void OnStart(string[] args)
 2         {
 3             Debugger.Launch();
 4 
 5             Timer timer = new Timer();
 6             timer.Interval = 1000;
 7             timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
 8             timer.Start();
 9 
10         }

  啓動服務後彈出以下:,而後選中對應的解決方案便可。

 

Demo下載

源碼下載

本文版權歸mephisto和博客園共有,歡迎轉載,但須保留此段聲明,並給出原文連接,謝謝合做。

相關文章
相關標籤/搜索