2013-12-17 53 views
0

我需要從Visual Studio中調試Windows服務我無法運行服務,因此我正在使用Installutil.exe。什麼是記錄信息或調試Windows服務的最簡單方法?

因此,每次構建後,我使用Installutil.exe,但我不能一步一步在我的代碼中。

你知道任何簡單的方法:

  • 使用VS調試器來檢查代碼?
  • 或在事件中記錄一些消息,以便我可以跟蹤發生了什麼?

感謝

+0

我通常使用一些AOP工具,如PostSharp插入'Trace.WriteLine'調用(你也可以自己做)。當我需要排除故障時,我設置了[Trace Listener](http://msdn.microsoft.com/en-us/library/4y5y10s7(v = vs.110).aspx)。 – vcsjones

回答

1

因此,在每次構建之後,我使用Installutil.exe,但是我無法通過 步執行我的代碼。

如果您想在Visual Studio中調試服務,那麼您可以執行以下操作。

Program.cs文件中定義:

private static void RunService() 
{ 
    var service = new YourService(); 
    System.ServiceProcess.ServiceBase.Run(service); 
} 

//for debug only 
private static void RunNoService() 
{ 
    using (var service = new YourService()) 
    { 
     service.Start(); 
     System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); 
    } 
} 

Main方法

static void Main() 
{ 
    if (Environment.UserInteractive) //This is IMPORTANT 
     RunNoService(); 
    else 
     RunService(); 
} 

在服務定義Start方法,這會從OnStart具備的功能,修改您的OnStart方法:

protected override void OnStart(string[] args) 
{ 
    Start(); 
} 

Environment.UserInteractive將檢查服務是否從Visual Studio運行並讓您調試它。

日誌記錄:

始終會記錄您的活動爲您服務。這將幫助您在服務生產中調試您的服務。您可以使用Log4Net或者您可以創建自己的自定義類以進行日誌記錄。即使記錄到一個簡單的文本文件將比沒有任何東西更好。但是你必須記錄日誌,否則如果在生產中出現錯誤,它可能會變得非常令人沮喪。

1

調試在Visual Studio中的服務,我使用此代碼的服務項目:

的Program.cs

static class Program 
    { 
#if DEBUG 
     static AutoResetEvent sare = new AutoResetEvent(false); 
#endif 

     static void Main() 
     { 
#if (!DEBUG)   
      ServiceBase[] ServicesToRun; 
      ServicesToRun = new ServiceBase[] { new Service() }; 
      ServiceBase.Run(ServicesToRun); 
#else 
      Service service = new Service(); 
      service.DebugServiceStopped += new Action(SetAutoResetEvent); 

      service.DebugStart(); 

      sare.WaitOne(); 
#endif 
     } 

#if DEBUG 
     private static void SetAutoResetEvent() 
     { 
      sare.Set(); 
     } 
#endif   
    } 

服務。CS(實際Service類的文件),你需要添加這些代碼部分:

#if DEBUG 
     public event Action DebugServiceStopped; 
     public void DebugStart() 
     { 
      OnStart(null); 
     } 
#endif 

     protected override void OnStop() 
     { 
#if DEBUG 
      DebugServiceStopped(); 
#endif 
     } 

如果選擇Debug在Visual Studio中的配置,你將能夠調試服務只是作爲一個正常的應用程序,否則項目將被編譯爲一個真正的服務。

記錄: 在Windows上存在Windows事件日誌用來存儲信息,警告和應用程序的錯誤。從服務的事件日誌可以寫入:

EventLog.WriteEntry("your log message", EventLogEntryType.Information); // or EventLogEntryType.Error,... depending on the entry type 
相關問題