2 changed files with 67 additions and 22 deletions
@ -0,0 +1,66 @@ |
|||||
|
using Apewer.Internals.Interop; |
||||
|
using System; |
||||
|
using System.Diagnostics; |
||||
|
using System.ServiceProcess; |
||||
|
|
||||
|
namespace Apewer.WinForm |
||||
|
{ |
||||
|
|
||||
|
/// <summary>Windows 服务。</summary>
|
||||
|
public class WindowsService : ServiceBase |
||||
|
{ |
||||
|
|
||||
|
Action on_start = null; |
||||
|
Action on_stop = null; |
||||
|
|
||||
|
/// <summary>创建 Windows 服务实例。</summary>
|
||||
|
/// <param name="serviceName">服务名称。</param>
|
||||
|
/// <param name="onStart">服务启动后,在后台线程执行的程序。</param>
|
||||
|
/// <param name="onStop">服务停止前,同步执行的程序。</param>
|
||||
|
/// <exception cref="ArgumentNullException"></exception>
|
||||
|
/// <exception cref="ArgumentException"></exception>
|
||||
|
public WindowsService(string serviceName, Action onStart, Action onStop) |
||||
|
{ |
||||
|
if (serviceName.IsEmpty()) throw new ArgumentNullException(nameof(serviceName)); |
||||
|
|
||||
|
ServiceName = serviceName; |
||||
|
on_start = onStart; |
||||
|
on_stop = onStop; |
||||
|
} |
||||
|
|
||||
|
/// <summary>创建 Windows 服务实例。</summary>
|
||||
|
/// <remarks>默认使用当前进程名称作为服务名称。</remarks>
|
||||
|
/// <param name="onStart">服务启动后,在后台线程执行的程序。</param>
|
||||
|
/// <param name="onStop">服务停止前,同步执行的程序。</param>
|
||||
|
/// <exception cref="ArgumentException"></exception>
|
||||
|
public WindowsService(Action onStart, Action onStop) : this(Process.GetCurrentProcess().ProcessName, onStart, onStop) { } |
||||
|
|
||||
|
/// <summary>服务启动时执行的程序。</summary>
|
||||
|
protected override void OnStart(string[] args) => RuntimeUtility.InBackground(on_start); |
||||
|
|
||||
|
/// <summary>服务停止时执行的程序。</summary>
|
||||
|
protected override void OnStop() => on_stop?.Invoke(); |
||||
|
|
||||
|
/// <summary>启动 Windows 服务实例。</summary>
|
||||
|
/// <param name="serviceName">服务名称。</param>
|
||||
|
/// <param name="onStart">服务启动后,在后台线程执行的程序。</param>
|
||||
|
/// <param name="onStop">服务停止前,同步执行的程序。</param>
|
||||
|
/// <exception cref="ArgumentNullException"></exception>
|
||||
|
/// <exception cref="ArgumentException"></exception>
|
||||
|
public static WindowsService Run(string serviceName, Action onStart, Action onStop = null) |
||||
|
{ |
||||
|
var service = new WindowsService(serviceName, onStart, onStop); |
||||
|
ServiceBase.Run(service); |
||||
|
return service; |
||||
|
} |
||||
|
|
||||
|
/// <summary>启动 Windows 服务实例。</summary>
|
||||
|
/// <remarks>默认使用当前进程名称作为服务名称。</remarks>
|
||||
|
/// <param name="onStart">服务启动后,在后台线程执行的程序。</param>
|
||||
|
/// <param name="onStop">服务停止前,同步执行的程序。</param>
|
||||
|
/// <exception cref="ArgumentException"></exception>
|
||||
|
public static WindowsService Run(Action onStart, Action onStop = null) => Run(Process.GetCurrentProcess().ProcessName, onStart, onStop); |
||||
|
|
||||
|
} |
||||
|
|
||||
|
} |
Loading…
Reference in new issue