是否有比通过Windows服务控制管理器启动服务,然后将调试器附加到线程更简单的方法来逐步遍历代码?这有点麻烦,我想知道是否有更直接的方法。


当前回答

如果我想快速调试服务,我只需在那里放入一个Debugger.Break()。当到达这条线时,它会将我拉回到VS.当你完成时,不要忘记删除这条线。

更新:作为#if DEBUG pragmas的替代,你也可以使用Conditional("DEBUG_SERVICE")属性。

[Conditional("DEBUG_SERVICE")]
private static void DebugMode()
{
    Debugger.Break();
}

在OnStart上,只需调用这个方法:

public override void OnStart()
{
     DebugMode();
     /* ... do the rest */
}

在那里,代码将只在调试构建期间启用。在此过程中,为服务调试创建一个单独的Build Configuration可能会很有用。

其他回答

我认为这取决于你使用的操作系统,Vista很难附加到服务,因为会话之间的分离。

我过去使用的两个选项是:

Use GFlags (in the Debugging Tools for Windows) to setup a permanent debugger for a process. This exists in the "Image File Execution Options" registry key and is incredibly useful. I think you'll need to tweak the Service settings to enable "Interact with Desktop". I use this for all types of debugging, not just services. The other option, is to separate the code a bit, so that the service part is interchangable with a normal app startup. That way, you can use a simple command line flag, and launch as a process (rather than a Service), which makes it much easier to debug.

希望这能有所帮助。


static void Main()
{
#if DEBUG
                // Run as interactive exe in debug mode to allow easy
                // debugging.

                var service = new MyService();
                service.OnStart(null);

                // Sleep the main thread indefinitely while the service code
                // runs in .OnStart

                Thread.Sleep(Timeout.Infinite);
#else
                // Run normally as service in release mode.

                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]{ new MyService() };
                ServiceBase.Run(ServicesToRun);
#endif
}

对于现有Windows服务程序的故障排除,请像其他人建议的那样使用'Debugger.Break()'。

对于新的Windows服务程序,我建议使用James Michael Hare的方法http://geekswithblogs.net/BlackRabbitCoder/archive/2011/03/01/c-toolbox-debug-able-self-installable-windows-service-template-redux.aspx

为了调试Windows服务,我结合了GFlags和一个由regedit创建的.reg文件。

运行GFlags,指定ex -name和vsjitdebugger 运行regedit并转到GFlags设置选项的位置 从文件菜单中选择“导出密钥” 将该文件保存在扩展名为.reg的某处 任何时候你想调试服务:双击.reg文件 如果要停止调试,请双击第二个.reg文件

或者保存以下代码片段并用所需的可执行名称替换servicename.exe。


debugon.reg:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\servicename.exe]
"GlobalFlag"="0x00000000"
"Debugger"="vsjitdebugger.exe"

debugoff.reg:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\servicename.exe]
"GlobalFlag"="0x00000000"

您有两个选项来进行调试。

创建一个日志文件:我个人更喜欢一个单独的日志文件,比如文本文件,而不是使用应用程序日志或事件日志。但是这将花费你大量的时间,因为它仍然很难找出准确的错误位置 将应用程序转换为控制台应用程序:这将使你能够在VS中使用所有的调试工具。

请参考我为这个主题创建的这篇博客文章。