Debugging services in C#

Recently, I have had to build a service for Windows and (not unlike everyone else who has tried to do this) I came across a hurdle of not being able to debug my service from the Visual Studio. I had to install the service manually, start it and debug it. Every time after the installation, I have to stop the service before I compile the code, then restart it again after the file has been copied. This can get very annoying if you have to do this multiple times a day. It’s a debugging nightmare for a developer.  However, you needn’t fear anymore as I have a solution to all of this chaos. You can edit Program.cs of  your project and insert this code in there :

 

    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            #if (!DEBUG)
            System.ServiceProcess.ServiceBase[] ServicesToRun;
            ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
            #else
            Service1 service = new Service1();
            service.Start();
            System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
            #endif 
        }
    }

 

What the code above will do is, if you are debugging your service, it will start your service as a thread and run it till you stop it. If you are compiling the code for a release, then it will run the whole thing as a regular Windows Service.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *