Attempting to debug a windows service can be a nightmare, especially if you are trying to debug the OnStart event by attaching to a local process. To get around this you can configure the windows service to launch as a console application. To do this go to the property pages of your service and select the Application tab. Change the output type to Console Application:
Next modify the program.cs file by adding an args input parameter to the Main method and surrounding the logic in the method with an if statement like so:
- static void Main(string[] args)
- {
- if (args.Length == 0)
- {
- ServiceBase[] ServicesToRun;
- ServicesToRun = new ServiceBase[]
- {
- new Service1()
- };
- ServiceBase.Run(ServicesToRun);
- }
- else
- {
- //DoWork();
- }
- }
Now modify your service1.cs file to call the same worker method on start:
- public partial class Service1 : ServiceBase
- {
- public Service1()
- {
- InitializeComponent();
- }
- protected override void OnStart(string[] args)
- {
- //DoWork();
- }
- protected override void OnStop()
- {
- }
- }
Finally go to the Debug tab on the property pages and add a word to the Command line arguments text box:
Now just start debugging and your breakpoint will be hit!

No comments:
Post a Comment