3

I want to debug window service. What should i write in main() to enable debugging in window service. I am developing window service using C#.

#if(DEBUG)
      System.Diagnostics.Debugger.Break();
      this.OnStart(null);
      System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
 #else
      ServiceBase.Run(this);
 #endif

i wrote above code segment but on line (this

2
  • Your question isn't complete. Commented Aug 9, 2011 at 11:44
  • Possible duplicate. Commented Aug 9, 2011 at 11:52

4 Answers 4

12

I personally use this method to debug a Windows service:

static void Main() {

    if (!Environment.UserInteractive) {
        // We are not in debug mode, startup as service

        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] { new MyServer() };
        ServiceBase.Run(ServicesToRun);
    } else {
        // We are in debug mode, startup as application

        MyServer service = new MyServer();
        service.StartService();
        System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
    }
}

And create a new method in your MyServer class that will use the OnStart event:

public void StartService() {
    this.OnStart(new string[0]);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

#if DEBUG
while (!System.Diagnostics.Debugger.IsAttached)
{
    Thread.Sleep(1000);
}
System.Diagnostics.Debugger.Break();
#endif

It waits until you attach a debugger, then breaks.

Comments

0

I would do it like this:
In your service's OnStart method add the call to Debugger.Break() at the top:

protected override void OnStart(string[] args)
{
    #if DEBUG
        Debugger.Break();
    #endif

    // ... the actual code
}

Comments

0

If you need to debug it without installing , In Program.cs class add below lines and make a breakpoint in function , then click F5

static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new Service1()
        };
        ServiceBase.Run(ServicesToRun);

         Service1 myService = new Service1();
         myService.CallMethodNeedDebuging();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.