using Apewer.Internals.Interop;
using System;
using System.Diagnostics;
using System.ServiceProcess;
namespace Apewer.WinForm
{
/// Windows 服务。
public class WindowsService : ServiceBase
{
Action on_start = null;
Action on_stop = null;
/// 创建 Windows 服务实例。
/// 服务名称。
/// 服务启动后,在后台线程执行的程序。
/// 服务停止前,同步执行的程序。
///
///
public WindowsService(string serviceName, Action onStart, Action onStop)
{
if (serviceName.IsEmpty()) throw new ArgumentNullException(nameof(serviceName));
ServiceName = serviceName;
on_start = onStart;
on_stop = onStop;
}
/// 创建 Windows 服务实例。
/// 默认使用当前进程名称作为服务名称。
/// 服务启动后,在后台线程执行的程序。
/// 服务停止前,同步执行的程序。
///
public WindowsService(Action onStart, Action onStop) : this(Process.GetCurrentProcess().ProcessName, onStart, onStop) { }
/// 服务启动时执行的程序。
protected override void OnStart(string[] args) => RuntimeUtility.InBackground(on_start);
/// 服务停止时执行的程序。
protected override void OnStop() => on_stop?.Invoke();
/// 启动 Windows 服务实例。
/// 服务名称。
/// 服务启动后,在后台线程执行的程序。
/// 服务停止前,同步执行的程序。
///
///
public static WindowsService Run(string serviceName, Action onStart, Action onStop = null)
{
var service = new WindowsService(serviceName, onStart, onStop);
ServiceBase.Run(service);
return service;
}
/// 启动 Windows 服务实例。
/// 默认使用当前进程名称作为服务名称。
/// 服务启动后,在后台线程执行的程序。
/// 服务停止前,同步执行的程序。
///
public static WindowsService Run(Action onStart, Action onStop = null) => Run(Process.GetCurrentProcess().ProcessName, onStart, onStop);
}
}