How do I debug Windows services in Visual Studio?

后端 未结 17 783
梦毁少年i
梦毁少年i 2020-11-28 03:56

Is it possible to debug the Windows services in Visual Studio?

I used code like

System.Diagnostics.Debugger.Break();

but it is givi

17条回答
  •  情书的邮戳
    2020-11-28 04:30

    I found this question, but I think a clear and simple answer is missing.

    I don't want to attach my debugger to a process, but I still want to be able to call the service OnStart and OnStop methods. I also want it to run as a console application so that I can log information from NLog to a console.

    I found these brilliant guides that does this:

    • Debugging a Windows Service Project

    • Easier way to debug a Windows service

    Start by changing the projects Output type to Console Application.

    Change your Program.cs to look like this:

    static class Program
    {
        /// 
        /// The main entry point for the application.
        /// 
        static void Main()
        {
            // Startup as service.
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };
    
            if (Environment.UserInteractive)
            {
                RunInteractive(ServicesToRun);
            }
            else
            {
                ServiceBase.Run(ServicesToRun);
            }
        }
    }
    

    Then add the following method to allow services running in interactive mode.

    static void RunInteractive(ServiceBase[] servicesToRun)
    {
        Console.WriteLine("Services running in interactive mode.");
        Console.WriteLine();
    
        MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart",
            BindingFlags.Instance | BindingFlags.NonPublic);
        foreach (ServiceBase service in servicesToRun)
        {
            Console.Write("Starting {0}...", service.ServiceName);
            onStartMethod.Invoke(service, new object[] { new string[] { } });
            Console.Write("Started");
        }
    
        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine(
            "Press any key to stop the services and end the process...");
        Console.ReadKey();
        Console.WriteLine();
    
        MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop",
            BindingFlags.Instance | BindingFlags.NonPublic);
        foreach (ServiceBase service in servicesToRun)
        {
            Console.Write("Stopping {0}...", service.ServiceName);
            onStopMethod.Invoke(service, null);
            Console.WriteLine("Stopped");
        }
    
        Console.WriteLine("All services stopped.");
        // Keep the console alive for a second to allow the user to see the message.
        Thread.Sleep(1000);
    }
    

提交回复
热议问题