关于调试windows service, 其实这是一个老生常谈的问题了.
通常的处理办法是, 在service运行后, 在调试器中选择attach to process.
然而这种做法也有一定的局限性, 例如在service启动时的OnStart事件中的代码, 基本上很难调试. 往往当attach到我们的service的时候, 这部分代码已经执行过了. 于是, 有人提出, 可以另写一个project来调用这个OnStart方法, 或将OnStart方法中的代码搬到另一个project中测试. 不过, 这些方法终究不是以windows服务的方式调试的, 不能够最真实的反应service运行时的执行状况(如权限问题等环境问题).
我的做法是, 在OnStart方法的最开始部分加上"Debugger.Launch()"的调用, 当service运行到此处时, 将会弹出一个选择调试器的对话框, 同时暂停在当前位置. 这样, 我们就做到了在代码中手动的启动调试器.
示例代码如下:
1 public partial class MyService : ServiceBase
2 {
3 public MyService()
4 {
5 InitializeComponent();
6 }
7 protected override void OnStart(string[] args)
8 {
9 #if DEBUG
10 Debugger.Launch(); //Launches and attaches a debugger to the process.
11 #endif
12 // TODO: add your initialize code here.
13 }
14 protected override void OnStop()
15 {
16 }
17 }
2 {
3 public MyService()
4 {
5 InitializeComponent();
6 }
7 protected override void OnStart(string[] args)
8 {
9 #if DEBUG
10 Debugger.Launch(); //Launches and attaches a debugger to the process.
11 #endif
12 // TODO: add your initialize code here.
13 }
14 protected override void OnStop()
15 {
16 }
17 }