Debug Windows Service

后端 未结 11 1425
既然无缘
既然无缘 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 18:09

    We can make the windows service project debuggable by just adding a parameter and making it behave like a console app.

    1) Go to your windows service project properties -> Debug -> Start Options 2) Give an argument -Console 3) Go to Application tab -> output type, change it to Console Application 4) Type the below code in Program.cs

    static class Program
        {
            private static EventWaitHandle _waitHandle;
            private static Service1 _service;
                    static void Main(string[] args)
            {
                bool runConsole = false;**
    
                foreach (string arg in args)
                {
                    if (arg.ToLowerInvariant().Equals("-console"))
                    {
                        runConsole = true;
                    }
                }   
    
                _service = new Service1();
                if (runConsole)
                {
                    _waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
                    Console.WriteLine("Starting Workflow Service in Console Mode");
                    Console.WriteLine("Press Ctrl+C to exit Console Mode");
                   Console.CancelKeyPress += new ConsoleCancelEventHandler(OnCancelKeyPress);
                    _service.InternalStart();
                    WaitHandle.WaitAll(new WaitHandle[] { _waitHandle });
                }
    
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new Service1() 
                };
                ServiceBase.Run(ServicesToRun);
            }
    
            static void OnCancelKeyPress(object sender, ConsoleCancelEventArgs e)
            {
                _service.InternalStop();
                _waitHandle.Set();
            }
    
    
        }
    

提交回复
热议问题