Windows服务调试小结(附Demo)
阅读目录
介绍
有时候不可避免的要建些Windows服务。既然写代码,就需要调试,由于这个东西搞的人不多,每个人调试的方法也不全,所以在下在这里小结一下调试方法。
搭建环境
一:创建一个Window Service
文件->新建项目->Windows 服务。
然后我们直接运行试试,然后提示如下:

好吧,我们就依他的意思,加个服务安装程序和些相关的引用及其他,结果如下:

这样我们的环境就基本搭建好了,然后就是服务的安装,运行bin\Debug\Install\install.bat即可。
调试方式
一:普通调试
msdn上指出“必须从服务控制管理器的上下文中而不是 Visual Studio 中运行服务。 因此,调试服务不像调试其他 Visual Studio 应用程序类型一样简单。 要调试服务,必须启动该服务,然后将调试器附加到该服务正在其中运行的进程中。 然后你可以使用所有 Visual Studio 的标准调试功能来调试你的应用程序”。
所以我们启动服务,然后通过vs附件该服务进程,然后就可以调试了。如下:


二:特殊调试
如果我们不想创建服务就想调试代码,其实可以采用其他的替代方式进行,只不过要改代码。
我们找到程序的入口: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

浙公网安备 33010602011771号