如何调试.NET Windows Service OnStart 方法? [英] How to debug the .NET Windows Service OnStart method?

查看:27
本文介绍了如何调试.NET Windows Service OnStart 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 .NET 编写的代码只有在作为 Windows 服务安装时才会失败.失败甚至不允许服务启动.我不知道如何进入 OnStart 方法.

I have code written in .NET that only fails when installed as a Windows service. The failure doesn't allow the service to even start. I can't figure out how I can step into the OnStart method.

如何:调试 Windows 服务应用程序 给出了一个诱人的线索:

How to: Debug Windows Service Applications gives a tantalizing clue:

附加到服务的进程允许您调试大部分但不是所有服务的代码;例如,因为服务已经启动,所以不能通过这种方式调试服务的OnStart方法中的代码,或者用于加载服务的Main方法中的代码.解决此问题的一种方法是在您的服务应用程序中创建一个临时的第二个服务,该服务仅用于帮助调试.您可以安装这两个服务,然后启动这个虚拟"服务来加载服务进程. 一旦临时服务启动了该进程,您就可以使用 Visual Studio 中的调试"菜单附加到服务进程.

Attaching to the service's process allows you to debug most but not all of the service's code; for example, because the service has already been started, you cannot debug the code in the service's OnStart method this way, or the code in the Main method that is used to load the service. One way to work around this is to create a temporary second service in your service application that exists only to aid in debugging. You can install both services, and then start this "dummy" service to load the service process. Once the temporary service has started the process, you can then use the Debug menu in Visual Studio to attach to the service process.

但是,我不清楚您应该如何创建虚拟服务来加载服务进程.

However, I'm not clear how it is exactly that you are supposed to create the dummy service to load the service process.

推荐答案

作为临时解决方法,您可以做的一件事是将调试器作为 OnStart 中的第一行代码启动

One thing you could do as a temporary workaround is to launch the debugger as the first line of code in the OnStart

System.Diagnostics.Debugger.Launch()

这将提示您选择要使用的调试器.只需在 Visual Studio 中打开解决方案,然后从列表中选择该实例即可.

This will prompt you for the debugger you'd like to use. Simply have the solution already open in Visual Studio and choose that instance from the list.

这篇关于如何调试.NET Windows Service OnStart 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆