How to debug the .NET Windows Service OnStart method?

后端 未结 16 1286
离开以前
离开以前 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:23

    Before I go in the topic one advise. Always use log specially if you are server side developer. Because there are some certain condition which you might not be able to produce while debugging the code in visual studio.

    Coming back to topic, I use Envoirnment.UserInteractive flag this is really handy see my code below

    public static void Main(string[] args)
    {
    
        if (System.Environment.UserInteractive)
        {
            string parameter = string.Concat(args);
    
            switch (parameter)
            {
                case "--install":
                    ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                    break;
                case "--uninstall":
                    ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                    break;
                default:
                    WindowsService service = new WindowsService();
                    service.OnStart(args);
                    Console.ReadKey();
                    service.OnStop();
                    break;
            }
        }
        else
        {
            ServiceBase.Run(new WindowsService());
        }
    }
    

    From visual studio you will get UserInteractive flag set so i would run it as console application, In addition to that even you can run product build by double clicking it and attaching debugger with it if you like to test it.

提交回复
热议问题