RaspberryIO/Unosquare.Swan/Extensions.WindowsServices.cs

75 lines
2.4 KiB
C#
Raw Normal View History

2019-02-17 14:08:57 +01:00
#if !NETSTANDARD1_3
2019-12-03 18:44:25 +01:00
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
2019-02-17 14:08:57 +01:00
#if NET452
2019-12-03 18:44:25 +01:00
using System.ServiceProcess;
2019-02-17 14:08:57 +01:00
#else
2019-12-03 18:44:25 +01:00
using Abstractions;
2019-02-17 14:08:57 +01:00
#endif
2019-12-03 18:44:25 +01:00
namespace Unosquare.Swan {
/// <summary>
/// Extension methods.
/// </summary>
public static class WindowsServicesExtensions {
2019-02-17 14:08:57 +01:00
/// <summary>
2019-12-03 18:44:25 +01:00
/// Runs a service in console mode.
2019-02-17 14:08:57 +01:00
/// </summary>
2019-12-03 18:44:25 +01:00
/// <param name="serviceToRun">The service to run.</param>
public static void RunInConsoleMode(this ServiceBase serviceToRun) {
if(serviceToRun == null) {
throw new ArgumentNullException(nameof(serviceToRun));
}
RunInConsoleMode(new[] { serviceToRun });
}
/// <summary>
/// Runs a set of services in console mode.
/// </summary>
/// <param name="servicesToRun">The services to run.</param>
public static void RunInConsoleMode(this ServiceBase[] servicesToRun) {
if(servicesToRun == null) {
throw new ArgumentNullException(nameof(servicesToRun));
}
const String onStartMethodName = "OnStart";
const String onStopMethodName = "OnStop";
MethodInfo onStartMethod = typeof(ServiceBase).GetMethod(onStartMethodName,
BindingFlags.Instance | BindingFlags.NonPublic);
MethodInfo onStopMethod = typeof(ServiceBase).GetMethod(onStopMethodName,
BindingFlags.Instance | BindingFlags.NonPublic);
List<Thread> serviceThreads = new List<Thread>();
"Starting services . . .".Info(Runtime.EntryAssemblyName.Name);
foreach(ServiceBase service in servicesToRun) {
Thread thread = new Thread(() => {
_ = onStartMethod.Invoke(service, new Object[] { new String[] { } });
$"Started service '{service.GetType().Name}'".Info(service.GetType());
});
serviceThreads.Add(thread);
thread.Start();
}
"Press any key to stop all services.".Info(Runtime.EntryAssemblyName.Name);
_ = Terminal.ReadKey(true, true);
"Stopping services . . .".Info(Runtime.EntryAssemblyName.Name);
foreach(ServiceBase service in servicesToRun) {
_ = onStopMethod.Invoke(service, null);
$"Stopped service '{service.GetType().Name}'".Info(service.GetType());
}
foreach(Thread thread in serviceThreads) {
thread.Join();
}
"Stopped all services.".Info(Runtime.EntryAssemblyName.Name);
}
}
2019-02-17 14:08:57 +01:00
}
#endif