Created
July 18, 2016 23:27
-
-
Save risingsunomi/6ab6ae55b04f6d1f5cc8443cacc82953 to your computer and use it in GitHub Desktop.
Program.cs for Windows Service with debugging template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.ServiceProcess; | |
using System.Text; | |
using System.Reflection; | |
using System.Threading; | |
namespace SomeService | |
{ | |
static class Program | |
{ | |
///<summery> | |
/// For debugging service via Visual Studio debugger | |
/// </summery> | |
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); | |
} | |
/// <summary> | |
/// The main entry point for the application. | |
/// </summary> | |
static void Main() | |
{ | |
ServiceBase[] ServicesToRun; | |
ServicesToRun = new ServiceBase[] | |
{ | |
new Service1() | |
}; | |
if (Environment.UserInteractive) | |
{ | |
RunInteractive(ServicesToRun); | |
} | |
else | |
{ | |
ServiceBase.Run(ServicesToRun); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment