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


当前回答

我使用了JOP的答案的变体。使用命令行参数,您可以在IDE中使用项目属性或通过Windows服务管理器设置调试模式。

protected override void OnStart(string[] args)
{
  if (args.Contains<string>("DEBUG_SERVICE"))
  {
    Debugger.Break();
  }
  ...
}

其他回答

使用Windows Service Template c#项目创建一个新的服务应用程序https://github.com/HarpyWar/windows-service-template

有控制台/服务模式自动检测,自动安装/卸载您的服务,包括几个最常用的功能。

您也可以通过命令提示符(sc.exe)启动服务。

就我个人而言,我会在调试阶段将代码作为独立程序运行,当大多数错误被解决后,再改为作为服务运行。

static class Program
{
    static void Main()
    {
        #if DEBUG

        // TODO: Add code to start application here

        //    //If the mode is in debugging
        //    //create a new service instance
        Service1 myService = new Service1();

        //    //call the start method - this will start the Timer.
        myService.Start();

        //    //Set the Thread to sleep
        Thread.Sleep(300000);

        //    //Call the Stop method-this will stop the Timer.
        myService.Stop();

         #else
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new Service1() 
        };

        ServiceBase.Run(ServicesToRun);
         #endif
    }
}

我过去所做的是有一个命令行开关,它可以作为服务或常规应用程序启动程序。然后,在我的IDE中,我将设置开关,以便我可以分步执行我的代码。

对于某些语言,您实际上可以检测它是否运行在IDE中,并自动执行此切换。

你在用什么语言?

对于现有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