How to debug Windows Service application

Jason Ge
2 min readJun 17, 2021

Debugging Windows service application can be very tricky. Some articles suggested to use VisualStudio to attach to the Windows service thread. But you have to first install the service locally and start it using Service Control Manager. It is quite cumbersome to do so.

In this article, we will discuss an easier way to debug Windows service. Assume we have a Notification service application:

The class Notifier.cs is where all the service functions defined. We can add 3 new public functions into this class.

  1. StartService(): This public function simply calls theprotected OnStart() function.
  2. StopService(): This public function simply calls the protected OnStop() function.
  3. ShutdownService(): This public function simply calls the protected OnShutdown() function.

In Program.cs file, we can add following code snippet:

If you start service in VisualStudio, it would not be able to accept console input since it is service application. We first need to change the project output type to “Console Application”

Now we can start the service application as console application. You can use the keyboard to start/stop/shutdown the service. You can put breakpoints inside your code and now you can debug your Windows service application!

Just remember you need to change your project output type back to “Windows Application” before release it to production.

If you don’t like to change the project output type, you can directly call the StartService() function and put the main thread to sleep forever as following code snippet.

#if DEBUG
var notifier = new Notifier();
notifier.StartService();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
......

You can find the demo Windows service application at here in Github.

Happy coding!

--

--

Jason Ge

Software developer with over 20 years experience. Recently focus on Vue/Angular and asp.net core.