How to debug Windows services in Visual Studio?

Is it possible to debug windows services in visual studio?

I used code like

System.Diagnostics.Debugger.Break(); 

but it gives some code error like

I got two errors: eventID 4096 VsJITDebugger and "Service does not respond to startup or control request in a timely manner."

+60
c # visual-studio visual-studio-2010 windows-services
Jan 13 '11 at 10:09
source share
13 answers

You can also try this.

  • Create your Windows service and install and run .... That is, Windows services must be running on your system.
  • While your service is running, go to the Debug menu, click the Attach process (or process in the old Visual Studio)
  • Find your current service and make sure that Show process from all users and Show processes in all sessions is selected, if not, select it.

enter image description here

  1. Click the Attach button
  2. Click OK
  3. Click Close
  4. Set a breakpoint at the desired location and wait for it to complete. It will automatically debug automatically when your code reaches this point.
  5. Remember, put a breakpoint in an accessible place if it is onStart (), then stop and start the service again

(After many searches, I found this in the section "How to Debug Windows Services in Visual Studio.")

+53
Jan 17 2018-11-11T00:
source share

Use the following code in the OnStart method:

 System.Diagnostics.Debugger.Launch(); 

Select a Visual Studio option from the pop-up message.

Note. . To use it only in debug mode, you can use the #if DEBUG compiler directive as follows. This will prevent accidental or debugging in Release mode on the Production server.

 #if DEBUG System.Diagnostics.Debugger.Launch(); #endif 
+92
Mar 28 '14 at 6:47
source share

You must select all the code that will make the material from the service project into a separate project, and then create a test application that you can run and debug normally.

The service design will be just the shell needed to implement the service part.

+20
Jan 13 '11 at 10:11
source share

Either this, as suggested by Lasse W. Carlsen, or set up a loop in your service that will wait for the debugger to join. Simplest -

 while (!Debugger.IsAttached) { Thread.Sleep(1000); } ... continue with code 

That way, you can start the service, and inside Visual Studio you select "Attach to Process ..." and join your service, which then resumes the normal checkout.

+13
Jan 13 '11 at 10:15
source share

Given that ServiceBase.OnStart has protected visibility, I took the reflection path to achieve debugging.

 private static void Main(string[] args) { var serviceBases = new ServiceBase[] {new Service() /* ... */ }; #if DEBUG if (Environment.UserInteractive) { const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic; foreach (var serviceBase in serviceBases) { var serviceType = serviceBase.GetType(); var methodInfo = serviceType.GetMethod("OnStart", bindingFlags); new Thread(service => methodInfo.Invoke(service, new object[] {args})).Start(serviceBase); } return; } #endif ServiceBase.Run(serviceBases); } 

Note that Thread is a foreground Thread by default. return ing from Main , while faux service threads are running, this will not end the process.

+4
Aug 16 '13 at 3:09 on
source share

You can create a console application. I use this main function:

  static void Main(string[] args) { ImportFileService ws = new ImportFileService(); ws.OnStart(args); while (true) { ConsoleKeyInfo key = System.Console.ReadKey(); if (key.Key == ConsoleKey.Escape) break; } ws.OnStop(); } 

My ImportFileService class is exactly the same as in my Windows application, except for inheritance ( ServiceBase ).

+2
Jan 13 '11 at 10:17
source share

You can also try the System.Diagnostics.Debugger.Launch () method. This helps when displaying the debugger pointer at the specified location, and you can debug the code.

Before this step, install your service.exe using the command line command line of Visual Studio - installutil projectservice.exe

Then start the service from the control panel โ†’ "Administration" โ†’ "Computer Management" โ†’ "Service and Application" โ†’ "Services" โ†’ "Name of your service"

+2
Aug 09 '13 at 9:56 on
source share

I use the / Console option in the Debug visual studio project> Launch Options> Command Line Arguments:

 public static class Program { [STAThread] public static void Main(string[] args) { var runMode = args.Contains(@"/Console") ? WindowsService.RunMode.Console : WindowsService.RunMode.WindowsService; new WinodwsService().Run(runMode); } } public class WindowsService : ServiceBase { public enum RunMode { Console, WindowsService } public void Run(RunMode runMode) { if (runMode.Equals(RunMode.Console)) { this.StartService(); Console.WriteLine("Press <ENTER> to stop service..."); Console.ReadLine(); this.StopService(); Console.WriteLine("Press <ENTER> to exit."); Console.ReadLine(); } else if (runMode.Equals(RunMode.WindowsService)) { ServiceBase.Run(new[] { this }); } } protected override void OnStart(string[] args) { StartService(args); } protected override void OnStop() { StopService(); } /// <summary> /// Logic to Start Service /// Public accessibility for running as a console application in Visual Studio debugging experience /// </summary> public virtual void StartService(params string[] args){ ... } /// <summary> /// Logic to Stop Service /// Public accessibility for running as a console application in Visual Studio debugging experience /// </summary> public virtual void StopService() {....} } 
+2
Mar 19 '15 at 20:22
source share

Unfortunately, if you try to debug something at the very beginning of the Windows service, "joining" to the running process will not work. I tried using Debugger.Break () as part of OnStart procecdure, but with the 64-bit compiled VS 10 application, the break command just throws this error:

 System error 1067 has occurred. 

At this point, you will need to install in your registry the option "Execution of the image file" for your executable file. It takes 5 minutes to set up and it works very well. Here is a link to MS where details are indicated:

http://msdn.microsoft.com/en-us/library/a329t4ed(v=vs.100).aspx

+1
Jul 10 '13 at 7:40
source share

I simply added this code to my service class to indirectly call OnStart, similar to OnStop.

  public void MyOnStart(string[] args) { OnStart(args); } 
+1
Sep 28 '13 at 16:50
source share

Has anyone tried VS's very own post-build event command line?

try adding this to post-build

 @echo off sc query "ServiceName" > nul if errorlevel 1060 goto install goto stop :delete echo delete sc delete "ServiceName" > nul echo %errorlevel% goto install :install echo install sc create "ServiceName" displayname= "Service Display Name" binpath= "$(TargetPath)" start= auto > nul echo %errorlevel% goto start :start echo start sc start "ServiceName" > nul echo %errorlevel% goto end :stop echo stop sc stop "ServiceName" > nul echo %errorlevel% goto delete :end 

if there is a build error with a message like Error 1 The command "@echo off sc query "ServiceName" > nul and so on, ctrl-c, then ctrl-v the error message in notepad and see the last sentence of the message.

can say exited with code x . find the code in some common error here and see how to solve it.

 1072 -- marked for deletion --> close all apps that maybe using the service including services.msc and windows event log. 1058 -- cant be started because disabled or has no enabled associated devices --> just delete it. 1060 -- doesnt exist --> just delete it. 1062 -- has not been started --> just delete it. 1053 -- didnt response to start or control --> see event log (if logged to event log). it maybe the service itself throw an exception 1056 -- service is already running --> stop the service then delete. 

more details about the error here

and if a build error with a message like

 Error 11 Could not copy "obj\x86\Debug\ServiceName.exe" to "bin\Debug\ServiceName.exe". Exceeded retry count of 10. Failed. ServiceName Error 12 Unable to copy file "obj\x86\Debug\ServiceName.exe" to "bin\Debug\ServiceName.exe". The process cannot access the file 'bin\Debug\ServiceName.exe' because it is being used by another process. ServiceName 

open cmd, then first try killing it taskkill /fi "services eq ServiceName" /f

if all is well, F5 should be sufficient to debug it.

+1
Mar 07 '16 at 18:45
source share

A Microsoft article explains how to debug a Windows service here and what part can be skipped if they debug it by joining a process.

Below is my working code. I followed the approach suggested by Microsoft.

Add this code to program.cs

  static void Main(string[] args) { // if block will execute when launched through Visual studio if (Environment.UserInteractive) { ServiceMonitor serviceRequest = new ServiceMonitor(); serviceRequest.TestOnStartAndOnStop(args); } else // This block will execute when code is compiled as windows application { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new ServiceMonitor() }; ServiceBase.Run(ServicesToRun); } } 

Add this code to the ServiceMonitor class.

 internal void TestOnStartAndOnStop(string[] args) { this.OnStart(args); Console.ReadLine(); this.OnStop(); } 

Now go to "Project Properties", select "Application" and select "Output Type" as "Console Application" when debugging or "Windows Application" when it is done when debugging, recompiling and installing your service. enter image description here

+1
Jul 12 '17 at 22:18
source share

The OnStart method does the following.

 protected override void OnStart(string[] args) { try { RequestAdditionalTime(600000); System.Diagnostics.Debugger.Launch(); // put brake point here. ............. your code } catch (Exception ex) { ......... your exception code } } 

then run the command prompt as administrator and enter the following

 c:\> sc create test-xyzService binPath= <ProjectPath>\bin\debug\service.exe type= own start= demand 

above line will create test-xyzService in the list of services

To start the service, you will be asked to attach your debut attachment to VS or not.

 c:\> sc start text-xyzService 

To stop the service

 c:\> sc stop test-xyzService 

To remove or delete

 c:\> sc delete text-xyzService 
0
Nov 09 '15 at 17:22
source share



All Articles