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


当前回答

使用TopShelf库。

创建一个控制台应用程序,然后在Main中配置安装

class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {

                // setup service start and stop.
                x.Service<Controller>(s =>
                {
                    s.ConstructUsing(name => new Controller());
                    s.WhenStarted(controller => controller.Start());
                    s.WhenStopped(controller => controller.Stop());
                });

                // setup recovery here
                x.EnableServiceRecovery(rc =>
                {
                    rc.RestartService(delayInMinutes: 0);
                    rc.SetResetPeriod(days: 0);
                });

                x.RunAsLocalSystem();
            });
        }
}

public class Controller
    {
        public void Start()
        {

        }

        public void Stop()
        {

        }
    }

要调试您的服务,只需在visual studio中按F5。

要安装服务,键入cmd "console.exe install"

然后,您可以在windows服务管理器中启动和停止服务。

其他回答

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

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

最好的选择是使用“系统”。诊断的名称空间。

将代码包含在if else块中,用于调试模式和发布模式,如下所示,在visual studio中切换调试和发布模式。

#if DEBUG  // for debug mode
       **Debugger.Launch();**  //debugger will hit here
       foreach (var job in JobFactory.GetJobs())
            {
                //do something 
            }

#else    // for release mode
      **Debugger.Launch();**  //debugger will hit here
     // write code here to do something in Release mode.

#endif

第一行的Debugger.Break()怎么样?

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

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

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

使用TopShelf库。

创建一个控制台应用程序,然后在Main中配置安装

class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {

                // setup service start and stop.
                x.Service<Controller>(s =>
                {
                    s.ConstructUsing(name => new Controller());
                    s.WhenStarted(controller => controller.Start());
                    s.WhenStopped(controller => controller.Stop());
                });

                // setup recovery here
                x.EnableServiceRecovery(rc =>
                {
                    rc.RestartService(delayInMinutes: 0);
                    rc.SetResetPeriod(days: 0);
                });

                x.RunAsLocalSystem();
            });
        }
}

public class Controller
    {
        public void Start()
        {

        }

        public void Stop()
        {

        }
    }

要调试您的服务,只需在visual studio中按F5。

要安装服务,键入cmd "console.exe install"

然后,您可以在windows服务管理器中启动和停止服务。