調試windows服務的OnStart方法
1.在OnStart方法內添加如下代碼
#if DEBUG
System.Diagnostics.Debugger.Launch();
#endif
完整的代碼如下
protected override void OnStart(string[] args)
{
#if DEBUG
System.Diagnostics.Debugger.Launch();
#endif
//add method code
}
2.在OnStart方法內打一個斷點
3.啓動服務,會命中OnStart方法內的那個斷點。
備註:Debugger.Launch()在static void Main()中,如下
static void Main()
{
#if DEBUG
System.Diagnostics.Debugger.Launch();
#endif
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new ServiceEmail()
};
ServiceBase.Run(ServicesToRun);
}
注意:因爲權限的問題,可能會選不到你所打開的Visual Studio,並且會打開一個新的Visual Studio,這個新的界面找不到代碼層,無法打斷點,解決方案是:以管理員的身份運行Visual Studio,然後再啓動服務,並在彈出選擇啓動Visual Studio的頁面,選擇你所進行調試的那個Visual Studio,千萬不要進行新建。