Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug a windows service using breakpoints?

I have a windows service with a timer. Its very hard to debug it. Because I start the service and put break points in different parts of the code. When I attach the process, I expect the service to start from the very beginning instead of some randome place in the middle code where I have break points. Its hard to debug like a normal application where you know the starting point. It appears that there are processes in the back ground that have not completed yet. So every single time, I start to debug, instead of starting from the very first break point, it starts from some random break point in the middle of application.

I want to know how windows service works in terms of processes, threads etc... and how can I start debugging from the beginning?

like image 726
dotnet-practitioner Avatar asked Apr 17 '09 16:04

dotnet-practitioner


3 Answers

I assume you're talking about .Net of course. I've always used the following code to debug my services. I place it where I want to the debugger to launch. Start the service and it automatically launches Visual Studio. Works well for me.

System.Diagnostics.Debugger.Launch();

System.Diagnostics.Debugger.Debug();

like image 63
Malik Daud Ahmad Khokhar Avatar answered Oct 05 '22 05:10

Malik Daud Ahmad Khokhar


Just press F5. You can run Windows Services regular just like apps.

Since we have no other command-line arguments we just use the presense of any command-line argument as a signal to run as a normal windows app. You could also require the presence of a specific command-line argument (i.e. /debug).

If sArgs IsNot Nothing AndAlso sArgs.Length > 0 Then
    ' If there are command-line args then run in non-service mode
    Dim svc As ServiceMain = New ServiceMain(True)
    svc.OnStart(Nothing)
    System.Windows.Forms.Application.Run()
    svc.OnStop()
Else
    ' If no command-line args then run normally
    Dim ServicesToRun() As System.ServiceProcess.ServiceBase
    ServicesToRun = New System.ServiceProcess.ServiceBase() {New ServiceMain(False)}
    System.ServiceProcess.ServiceBase.Run(ServicesToRun)
End If
like image 45
MattH Avatar answered Oct 05 '22 03:10

MattH


You can use "Image File Execution Options" and configure that each time that the service start it would start inside a debugger.
That debugger can be WinDBG or Visual Studio.

like image 39
Shay Erlichmen Avatar answered Oct 05 '22 03:10

Shay Erlichmen