Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug the .NET Windows Service OnStart method?

Tags:

c#

.net

debugging

I have code written in .NET that only fails when installed as a Windows service. The failure doesn't allow the service to even start. I can't figure out how I can step into the OnStart method.

How to: Debug Windows Service Applications gives a tantalizing clue:

Attaching to the service's process allows you to debug most but not all of the service's code; for example, because the service has already been started, you cannot debug the code in the service's OnStart method this way, or the code in the Main method that is used to load the service. One way to work around this is to create a temporary second service in your service application that exists only to aid in debugging. You can install both services, and then start this "dummy" service to load the service process. Once the temporary service has started the process, you can then use the Debug menu in Visual Studio to attach to the service process.

However, I'm not clear how it is exactly that you are supposed to create the dummy service to load the service process.

like image 380
Nathan Avatar asked Jul 28 '09 20:07

Nathan


People also ask

How do you debug a method in C#?

To start debugging, select F5, or choose the Debug Target button in the Standard toolbar, or choose the Start Debugging button in the Debug toolbar, or choose Debug > Start Debugging from the menu bar. The app starts and the debugger runs to the line of code where you set the breakpoint.

How do I debug a Windows service without installing?

To debug without installing, add the code as follow, mainly #if (! DEBUG). You will be able to step through the code when you run the Windows Service without installing.


1 Answers

One thing you could do as a temporary workaround is to launch the debugger as the first line of code in the OnStart

System.Diagnostics.Debugger.Launch() 

This will prompt you for the debugger you'd like to use. Simply have the solution already open in Visual Studio and choose that instance from the list.

like image 189
palehorse Avatar answered Sep 30 '22 05:09

palehorse