How do I debug Windows services in Visual Studio?

后端 未结 17 745
梦毁少年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:28

    A Microsoft article explains how to debug a Windows service here and what part anyone can miss if they debug it by attaching to a process.

    Below is my working code. I have followed the approach suggested by Microsoft.

    Add this code to program.cs:

    static void Main(string[] args)
    {
        // 'If' block will execute when launched through Visual Studio
        if (Environment.UserInteractive)
        {
            ServiceMonitor serviceRequest = new ServiceMonitor();
            serviceRequest.TestOnStartAndOnStop(args);
        }
        else // This block will execute when code is compiled as a Windows application
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new ServiceMonitor()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
    

    Add this code to the ServiceMonitor class.

    internal void TestOnStartAndOnStop(string[] args)
    {
        this.OnStart(args);
        Console.ReadLine();
        this.OnStop();
    }
    

    Now go to Project Properties, select tab "Application" and select Output Type as "Console Application" when debugging, or "Windows Application" when done with debugging, recompile and install your service.

提交回复
热议问题