This repository has been archived by the owner on Dec 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 308
/
Copy pathServiceBaseLifetime.cs
64 lines (55 loc) · 1.99 KB
/
ServiceBaseLifetime.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#if NET461
using System;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace GenericHostSample
{
public static class ServiceBaseLifetimeHostExtensions
{
public static IHostBuilder UseServiceBaseLifetime(this IHostBuilder hostBuilder)
{
return hostBuilder.ConfigureServices((hostContext, services) => services.AddSingleton<IHostLifetime, ServiceBaseLifetime>());
}
public static Task RunAsServiceAsync(this IHostBuilder hostBuilder, CancellationToken cancellationToken = default)
{
return hostBuilder.UseServiceBaseLifetime().Build().RunAsync(cancellationToken);
}
}
public class ServiceBaseLifetime : ServiceBase, IHostLifetime
{
private Action<object> _startCallback;
private Action<object> _stopCallback;
private object _startState;
private object _stopState;
public void RegisterDelayStartCallback(Action<object> callback, object state)
{
_startCallback = callback ?? throw new ArgumentNullException(nameof(callback));
_startState = state ?? throw new ArgumentNullException(nameof(state));
Run(this);
}
public void RegisterStopCallback(Action<object> callback, object state)
{
_stopCallback = callback ?? throw new ArgumentNullException(nameof(callback));
_stopState = state ?? throw new ArgumentNullException(nameof(state));
}
public Task StopAsync(CancellationToken cancellationToken)
{
Stop();
return Task.CompletedTask;
}
protected override void OnStart(string[] args)
{
_startCallback(_startState);
base.OnStart(args);
}
protected override void OnStop()
{
_stopCallback(_stopState);
base.OnStop();
}
}
}
#endif