Debugging windows services

后端 未结 5 849
抹茶落季
抹茶落季 2020-12-10 20:55

I have created a windows service and installed it manually. Later started the service from Services tool. Now I want to dubug the windows service application from Visual st

5条回答
  •  一生所求
    2020-12-10 21:31

    This doesn't answer the exact question, but for what it's worth, I have found the easiest way to develop and debug a windows service is to put all of the logic into a class library and then call the logic from either a windows service (in production) or from a regular windows form (during development). The windows form would have a Start and Stop button which would simulate the start and stop behavior of the service.

    To make it easy to switch between the two modes, I just use a command line parameter and handle that in the Main method like this:

    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 
        private static void Main(string[] args)
        {
            if (args.Length > 0 && args[0] == "/form")
            {
                var form = new MainForm();
                Application.Run(form);
                return;
            }
    
            var servicesToRun = new ServiceBase[]
            {
                new BackgroundService()
            };
    
            ServiceBase.Run(servicesToRun);
        }
    }
    

    Then in the "Command line arguments" field of the Visual Studio project properties, you can just add the "/form" parameter, and it will always pop up the form when debugging locally. This way you don't have to worry about attaching to a process or anything like that. You just click Debug as usual, and you're good to go.

提交回复
热议问题