How to debug the .NET Windows Service OnStart method?
Solution 1:
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.
Solution 2:
I tend to add a method like this:
[Conditional("DEBUG")]
private void AttachDebugger()
{
Debugger.Break();
}
it will only get called on Debug builds of you project and it will pause execution and allow you to attach the debugger.
Solution 3:
Once you have a service that is installed using installutil.exe
, you can alter the Start Parameters
to jump into the debugger if the service is started:
When you manually start the service with the parameter -debugWithVisualStudio
(or simply -d
), it will automatically detect the correct project, and fire up the interactive debugger in Visual Studio:
To support this functionality, change the service's OnStart()
function:
/// <summary>
/// Executed when the service is started.
/// </summary>
/// <param name="args">Command line arguments.</param>
protected override void OnStart(string[] args)
{
try
{
//How to debug when running a Windows Service:
// 1. Right click on the service name in Windows Service Manager.
// 2. Select "Properties".
// 3. In "Start Parameters", enter "-d" (or "-debugWithVisualStudio").
// 4. Now, when you start the service, it will fire up Visual Studio 2012 and break on the line below.
// 5. Make sure you have UAC (User Access Control) turned off, and have Administrator privileges.
#if DEBUG
if (((ICollection<string>)args).Contains("-d")
|| ((ICollection<string>)args).Contains("-debugWithVisualStudio"))
{
Debugger.Launch(); // Launches VS2012 debugger.
}
#endif
ShellStart(args);
base.OnStart(args);
}
catch (Exception ex)
{
// Log exception here.
}
}
(optional) If you want to narrow down to the exact line of code where the service is throwing an error, switch on exceptions from the Visual Studio menu DEBUG .. Exceptions
. When you continue debugging, it will break on the exact line that is throwing the exception.
Solution 4:
It works just fine!
protected override void OnStart(string[] args)
{
System.Diagnostics.Debugger.Launch();
}