Debug Windows Service

后端 未结 11 1421
既然无缘
既然无缘 2020-11-29 17:09

Scenario

I\'ve got a windows service written in C#. I\'ve read all the google threads on how to debug it, but I still can\'t get it to work. I\'ve run \"PathTo.Net

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 17:51

    In order to be able to debug my service without deploying it, I always write it in the following way:

    In your program.cs file:

    #if DEBUG
        MyService myService = new MyService();
        myService.OnDebug();
        System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
    #else
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new MyService()
        };
        ServiceBase.Run(ServicesToRun);
    #endif
    

    and in your MyService.cs file:

        public void OnDebug()
        {
            OnStart(null);
        }
    

    * NOTE *: You must build under 'Release' mode when you are finally done with debugging and you are ready to deploy the service otherwise the service will not be considered as a service.

    Hope this helps.

提交回复
热议问题