How to debug the .NET Windows Service OnStart method?

后端 未结 16 1307
离开以前
离开以前 2020-12-01 00:13

I have code written in .NET that only fails when installed as a Windows service. The failure doesn\'t allow the service to even start. I can\'t figure out how I can step int

16条回答
  •  孤城傲影
    2020-12-01 00:27

    I know this is late but this is how we handle debuging Windows services

    First create a class which will act as the service.

    Add the appropriate methods for starting, stopping, pausing, etc...

    Add a windows form to the service project.

    In the service code create the service class created above and make the calls needed to start and stop the service in the ServiceBase class

    Open the Program.cs and add the following

    #if DEBUG
        [STAThread]
    #endif
        static void Main()
        {
    try
            {
    #if DEBUG
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new DebugForm());
    #else
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
            { 
                new YourWindowsService() 
            };
                ServiceBase.Run(ServicesToRun);
    #endif
            }
            catch (Exception e)
            {
                logger.Error(DateTime.Now.ToString() + " - " + e.Source + " - " + e.ToString() + "\r\n------------------------------------\r\n");
            }
    }
    

    When you run in DEBUG mode the windows form will launch. Just remember to build in Release mode when finished. Of course the conditional compile variable can be anything you like. You could even create seperate projects so the debug form is its own project.

    Hope this helps

提交回复
热议问题