Debugging windows service without consuming code from another app
Is it possible to debug a windows service or class library without consuming the code in a launchable app? There is a thread about doing this, but the techniques don't开发者_运维百科 work and keep saying "Cannot start service..." as I am using a windows service.
Thanks
Are you writing the service in the first place? If so, do yourself a favor and use TopShelf. It will let you create a simple console app that you can debug as a console app, but it can also get registered as a service and run as such.
Massively convenient in my experience as you can easily debug the service if needed without changing any code.
In you main function, rather than calling ServiceBase.Run(servicesToRun)
, just run the actual code you want to test.
I usually put in code to check for a command line parameter as in:
-c run in console mode
-i install the service
-u uninstall the service
none run the service
And then set up VS to send in -c while in debug mode.
Here's a bit of code that you can use to attach a debugger. I have found it difficult to attach a debugger at the start of the process in the past. When I found this fantastic snip on CodeProject I believe.
Anyway, add this into OnStart, build, install and start your service. Once you have started it will look like it has hung. Attach to the service process (making sure you have the correct Attach to code base selected and presto you can even debug start up.
protected override void OnStart(string[] args)
{
#if DEBUG
while (!Debugger.IsAttached) // Waiting until debugger is attached
{
RequestAdditionalTime(1000); // Prevents the service from timeout
Thread.Sleep(1000); // Gives you time to attach the debugger
}
RequestAdditionalTime(20000); // for Debugging the OnStart method,
// increase as needed to prevent timeouts
#endif
// here is your startup code with breakpoints
}
HTH
精彩评论