如何调试windows服务

如何调试windows服务

在开发windows服务时,直接启动服务不便于调试,可以添加一个调试模式。

代码Service1 .cs

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

using System;

using System.ServiceProcess;

namespace DebuggableService1

{

public partial class Service1 : ServiceBase

{

public Service1()

{

InitializeComponent();

}

public void StartDebug(string[] args) => OnStart(args);

public void StopDebug() => OnStop();

protected override void OnStart(string[] args)

{

Console.WriteLine("Service Started.");

}

protected override void OnStop()

{

Console.WriteLine("Service Stopped.");

}

}

}

Program.cs

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

using System.ServiceProcess;

using System.Threading;

//给以下代码添加注释

namespace DebuggableService1

{

internal static class Program

{

static void Main()

{

var service = new Service1();

if (System.Environment.UserInteractive)

{

var wh = new EventWaitHandle(false, EventResetMode.AutoReset, "StopService");

service.StartDebug(null);

wh.WaitOne();

service.StopDebug();

}

else

{

ServiceBase.Run(service);

}

}

}

}

停止调试运行的服务 Stop-DebugService.ps1

1

2

3

4

#定义EventWaitHandle类型变量wh,调用OpenExisting()方法传入字符串“StopService”

$wh = [System.Threading.EventWaitHandle]::OpenExisting("StopService")

#调用wh的Set()方法

$wh.Set()

这两行代码的作用是: 通过EventWaitHandle的OpenExisting()静态方法打开名为“StopService”的事件,调用Set()方法设置“StopService”事件,意思是通知等待该事件的线程可以继续执行了,用于停止服务。

参考资料

WindowsのServiceを簡単にデバッグする方法 本文会经常更新,请阅读原文: https://dashenxian.github.io/post/%E5%A6%82%E4%BD%95%E8%B0%83%E8%AF%95windows%E6%9C%8D%E5%8A%A1 ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 小神仙 (包含链接: https://dashenxian.github.io ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 (125880321@qq.com) 。

相关文章

2025年京东618手机便宜吗?为什么618买手机便宜?
beat365手机版官方

2025年京东618手机便宜吗?为什么618买手机便宜?

📅 07-01 👁️ 7862
掌握战法创新“四字诀”
365平台赌博

掌握战法创新“四字诀”

📅 07-08 👁️ 4651