Skip to content

Instantly share code, notes, and snippets.

@dguder
Created May 7, 2013 08:18
Show Gist options
  • Save dguder/5531039 to your computer and use it in GitHub Desktop.
Save dguder/5531039 to your computer and use it in GitHub Desktop.
Runs a service from console for debugging
// The main entry point for the process
static void Main()
{
#if (!DEBUG)
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
#else
// Debug code: this allows the process to run as a non-service.
// It will kick off the service start point, but never kill it.
// Shut down the debugger to exit
Service1 service = new Service1();
service.<Your Service's Primary Method Here>();
// Put a breakpoint on the following line to always catch
// your service when it has finished its work
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif
}
static void Main()
{
ServiceBase[] servicesToRun;
servicesToRun = new ServiceBase[]
{
new MyService()
};
if (Environment.UserInteractive)
{
RunInteractive(servicesToRun);
}
else
{
ServiceBase.Run(servicesToRun);
}
}
// The RunInteractive helper uses reflection to call the protected OnStart and OnStop methods:
static void RunInteractive(ServiceBase[] servicesToRun)
{
Console.WriteLine("Services running in interactive mode.");
Console.WriteLine();
MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart",
BindingFlags.Instance | BindingFlags.NonPublic);
foreach (ServiceBase service in servicesToRun)
{
Console.Write("Starting {0}...", service.ServiceName);
onStartMethod.Invoke(service, new object[] { new string[] { } });
Console.Write("Started");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(
"Press any key to stop the services and end the process...");
Console.ReadKey();
Console.WriteLine();
MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop",
BindingFlags.Instance | BindingFlags.NonPublic);
foreach (ServiceBase service in servicesToRun)
{
Console.Write("Stopping {0}...", service.ServiceName);
onStopMethod.Invoke(service, null);
Console.WriteLine("Stopped");
}
Console.WriteLine("All services stopped.");
// Keep the console alive for a second to allow the user to see the message.
Thread.Sleep(1000);
}
@sin2akshay
Copy link

Are these both different ways of debugging a service?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment