如何调试.NET Windows服务OnStart方法?

Nat*_*han 54 .net c# debugging

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

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

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

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

pal*_*rse 97

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

System.Diagnostics.Debugger.Launch()
Run Code Online (Sandbox Code Playgroud)

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

  • 我把Debugger.Launch放在main方法中,现在我可以进入代码了.谢谢! (2认同)

Has*_*niH 10

我倾向于添加这样的方法:

    [Conditional("DEBUG")]
    private void AttachDebugger()
    {
        Debugger.Break();
    }
Run Code Online (Sandbox Code Playgroud)

它只会在你项目的Debug版本上被调用,它会暂停执行并允许你附加调试器.


Con*_*ngo 8

获得使用后安装的服务后,如果服务已启动installutil.exe,您可以更改Start Parameters为跳转到调试器:

在此输入图像描述

当您使用参数-debugWithVisualStudio(或简单地-d)手动启动服务时,它将自动检测正确的项目,并在Visual Studio中启动交互式调试器:

在此输入图像描述

要支持此功能,请更改服务的OnStart()功能:

/// <summary>
///     Executed when the service is started.
/// </summary>
/// <param name="args">Command line arguments.</param>
protected override void OnStart(string[] args)
{
    try
    {
        //How to debug when running a Windows Service:
        // 1. Right click on the service name in Windows Service Manager.
        // 2. Select "Properties".
        // 3. In "Start Parameters", enter "-d" (or "-debugWithVisualStudio").
        // 4. Now, when you start the service, it will fire up Visual Studio 2012 and break on the line below.
        // 5. Make sure you have UAC (User Access Control) turned off, and have Administrator privileges.
#if DEBUG
        if (((ICollection<string>)args).Contains("-d")
            || ((ICollection<string>)args).Contains("-debugWithVisualStudio"))
        {
            Debugger.Launch(); // Launches VS2012 debugger.
        }
#endif
        ShellStart(args);
        base.OnStart(args);
    }
    catch (Exception ex)
    {
        // Log exception here.
    }
}
Run Code Online (Sandbox Code Playgroud)

(可选)如果要缩小服务引发错误的确切代码行,请从Visual Studio菜单中切换异常DEBUG .. Exceptions.当您继续调试时,它将在抛出异常的确切行上中断.

在此输入图像描述


Dev*_*per 7

它工作得很好!

protected override void OnStart(string[] args)
{
    System.Diagnostics.Debugger.Launch();
}
Run Code Online (Sandbox Code Playgroud)


Bor*_*nek 5

上面的选项似乎不适用于Windows 8.

我添加了Thread.Sleep(15000); 进入我的OnStart()方法并在代码的下一行设置断点.这使我在启动服务后将VS调试器附加到我的进程15秒,并允许我很好地调试OnStart()方法.