2010-01-14 98 views
2

我想在Windows XP機器上調試Visual Studio 2005中的Windows服務。我可以安裝Windows服務並從管理控制檯啓動它。但是,進程在可用進程列表中顯示爲禁用,我無法將調試器附加到它。我能做些什麼來啓用可用進程列表中的進程?調試Windows服務

謝謝!

回答

1

您可能沒有權限附加到進程。確保您已從管理帳戶啓動Visual Studio。

+0

+1正要說這個。 – 2010-01-14 04:39:05

3

我有一個小竅門,允許輕鬆調試。它基本上把服務變成一個命令行應用程序,所以你可以調試它。下面是代碼:

一下添加到Program.cs中(無效的主要()

#if (!DEBUG) 
    ServiceBase[] ServicesToRun; 
    ServicesToRun = new ServiceBase[] { new PollingService() }; 
    ServiceBase.Run(ServicesToRun); 
#else 
    // Debug code: this allows the process to run as a non-service. 
    MyService service = new MyServiceService(); 
    service.OnStart(null); 

    //Use this to make the service keep running 
    // Shut down the debugger to exit 
    System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); 

    //Use this to make it stop 
    //System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10)); 
    //service.OnStop(); 
#endif 

然後添加這在服務OnStart方法內:

#if (!DEBUG) 
    protected override void OnStart(string[] args) 
#else 
    public new void OnStart(string[] args) 
#endif 

,這對調用OnStop方法

#if (!DEBUG) 
    protected override void OnStop() 
#else 
    public new void OnStop() 
#endif 
3

有一對夫婦在這裏有用的選項。

首先,我會建議爲所有的Windows服務編寫Main()例程,以支持將它們作爲Windows服務或控制檯應用程序運行。這樣,您可以在控制檯上運行,以便更輕鬆地進行調試。一個簡化的main()例程看起來是這樣的:

private static void Main(string[] args) 
    { 
     _service = new Service(); 

     if (args.Length == 0 && !Debugger.IsAttached) 
     { 
      Run(new ServiceBase[] {_service}); 
     } 
     else 
     { 
      Console.WriteLine("Starting Service..."); 
      _service.OnStart(new string[0]); 
      Console.WriteLine("Service is running... Hit ENTER to break."); 
      Console.ReadLine(); 
      _service.OnStop(); 
     } 
    } 

您可以更大膽,並支持不同的參數對於像幫助,控制檯,服務,安裝,卸載。

另一種選擇是在代碼中添加一個Debugger.Break()語句。然後,您可以像平常一樣運行該服務,當它達到該點時,它將提示用戶附加一個調試器。

+0

這正是我所需要的。 – 2010-02-24 10:25:55

+0

爲了這個工作,OnStart和OnStop必須從'protected override'更改爲'public new' – 2011-04-15 22:54:45

+0

@Gabriel McAdams,如果您將Main類放入服務中,則不行。 – 2011-04-17 14:45:16