Easier way to debug a Windows service

后端 未结 28 1918
春和景丽
春和景丽 2020-11-22 15:36

Is there an easier way to step through the code than to start the service through the Windows Service Control Manager and then attaching the debugger to the thread? It\'s ki

28条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 16:26

    Use the TopShelf library.

    Create a console application then configure setup in your Main

    class Program
        {
            static void Main(string[] args)
            {
                HostFactory.Run(x =>
                {
    
                    // setup service start and stop.
                    x.Service(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()
            {
    
            }
        }
    

    To debug your service, just hit F5 in visual studio.

    To install service, type in cmd "console.exe install"

    You can then start and stop service in the windows service manager.

提交回复
热议问题