I created a Windows service in .Net, but for some reason it does not work for me. Is there any way to know what is failing and to debug it?
I created a Windows service in .Net, but for some reason it does not work for me. Is there any way to know what is failing and to debug it?
Debugging a Service is not as simple as debugging other applications, since it does not run in the context of Visual Studio. But there are several ways to do it:
Associate the debugger with the service process:
Herramientas
, Opciones
. In the Opciones
dialog box, choose Depuración
, Símbolos
, check the% Servidores de símbolos de Microsoft
box, and then choose the Aceptar
button. Asociar al proceso
in the Debug menu or Tools. (Keyboard: Ctrl + Alt + P)
The Processes dialog will appear. Mostrar los procesos de todos los usuarios
box. Procesos disponibles
section, choose the service process, and then select Asociar
.
The Asociar al proceso
dialog box will appear. Choose the appropriate options, and then choose Aceptar
to close the dialog box.
Set the breakpoints you want to use in the code.
Run a Windows service as a console application
Add a method to the service that runs the OnStart and OnStop methods:
internal void TestStartupAndStop(string[] args)
{
this.OnStart(args);
Console.ReadLine();
this.OnStop();
}
Rewrite the Main method as follows:
static void Main(string[] args)
{
if (Environment.UserInteractive)
{
MyNewService service1 = new MyNewService(args);
service1.TestStartupAndStop(args);
}
else
{
// Pon el código que tenías antes aquí
}
}
Aplicación
tab of the project properties, set the Output type to Aplicación de consola
. Iniciar depuración (F5)
. Use Debugger.Break
or Debugger.Launch
This is a very simple method. Simply add Debugger.Break
or Debugger.Launch
in the place where you want the execution of the service to stop and automatically launch the visual studio with the execution stopped at that point. From there, you can debug the service step by step.
Launch from services.msc
Another option is to compile the service in debug mode and put a breakpoint where you want the debugger to be launched. Once that is done, the service must be installed to later launch it from services.msc
. At that time, the system will pre-register if you want to open it with Visual Studio. Answering affirmatively you can already debug the service. ( Thanks to @Veelicus )
Finally, it depends on the error that the service is giving, it is possible that we can find it in the System Event Log, and we could also capture the exceptions ourselves and add them to this log or to our own log. For more information on how to write in the Windows Event Log, see [this site]. ( link )
Information obtained from MSDN and StackOverflow