I\'ve got a windows service written in C#. I\'ve read all the google threads on how to debug it, but I still can\'t get it to work. I\'ve run \"PathTo.Net
I recently added this to a project and it works great for me. You can debug it just like any other EXE. After it is added go to your project properties and add a command line parameter (/EXE) in the Debug tab for the Debug build configuration.
<MTAThread()> _
Shared Sub Main()
''
'' let's add a command line parameter so we can run this as a regular exe or as a service
''
If Command().ToUpper() = "/EXE" Then
Dim app As MyService = New MyService()
app.OnStart(Nothing)
Application.Run()
Else
Dim ServicesToRun() As System.ServiceProcess.ServiceBase
' More than one NT Service may run within the same process. To add
' another service to this process, change the following line to
' create a second service object. For example,
'
' ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
'
ServicesToRun = New System.ServiceProcess.ServiceBase() {New MyService}
System.ServiceProcess.ServiceBase.Run(ServicesToRun)
End If
End Sub
In order to be able to debug my service without deploying it, I always write it in the following way:
In your program.cs file:
#if DEBUG
MyService myService = new MyService();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
#endif
and in your MyService.cs file:
public void OnDebug()
{
OnStart(null);
}
* NOTE *: You must build under 'Release' mode when you are finally done with debugging and you are ready to deploy the service otherwise the service will not be considered as a service.
Hope this helps.
I recommend following pattern for debug:
var ServiceToRun = new SomeService();
if (Environment.UserInteractive)
{
// This used to run the service as a console (development phase only)
ServiceToRun.Start();
Console.WriteLine("Press Enter to terminate ...");
Console.ReadLine();
ServiceToRun.DoStop();
}
else
{
ServiceBase.Run(ServiceToRun);
}
Edit: make sure that your target is Console Application, not Windows Application, otherwise it will not work.
If you create your service with TopShelf you should be able to easily debug it from Visual Studio
This has helped me a lot when developing/debugging windows services:
http://windowsservicehelper.codeplex.com/
Just press F5 to debug. Very easy.
Andrey's approach is also very good.
I recommend to add /test
on project properties debug tab as a start option. Then you can run your service without having to install it.