/
Host.cs
325 lines (277 loc) · 10 KB
/
Host.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
using System.Runtime.InteropServices;
using NewLife.Log;
namespace NewLife.Model;
/// <summary>轻量级主机服务</summary>
/// <remarks>
/// 文档 https://newlifex.com/core/host
/// </remarks>
public interface IHostedService
{
/// <summary>开始服务</summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task StartAsync(CancellationToken cancellationToken);
/// <summary>停止服务</summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task StopAsync(CancellationToken cancellationToken);
}
/// <summary>主机服务扩展</summary>
public static class HostedServiceExtensions
{
/// <summary>注册主机服务,在主机启动和停止时执行</summary>
/// <typeparam name="THostedService"></typeparam>
/// <param name="services"></param>
/// <returns></returns>
public static IObjectContainer AddHostedService<THostedService>(this IObjectContainer services) where THostedService : class, IHostedService
{
services.AddSingleton<IHostedService, THostedService>();
return services;
}
/// <summary>注册主机服务,在主机启动和停止时执行</summary>
/// <typeparam name="THostedService"></typeparam>
/// <param name="services"></param>
/// <param name="implementationFactory"></param>
/// <returns></returns>
public static IObjectContainer AddHostedService<THostedService>(this IObjectContainer services, Func<IServiceProvider, THostedService> implementationFactory) where THostedService : class, IHostedService
{
services.AddSingleton<IHostedService>(implementationFactory);
return services;
}
}
/// <summary>轻量级应用主机</summary>
/// <remarks>
/// 文档 https://newlifex.com/core/host
/// 销毁主机时,会触发所有服务的停止事件
/// </remarks>
public interface IHost
{
/// <summary>添加服务</summary>
/// <param name="service"></param>
void Add(IHostedService service);
/// <summary>添加服务</summary>
/// <typeparam name="TService"></typeparam>
void Add<TService>() where TService : class, IHostedService;
/// <summary>同步运行,大循环阻塞</summary>
void Run();
/// <summary>异步允许,大循环阻塞</summary>
/// <returns></returns>
Task RunAsync();
/// <summary>关闭主机</summary>
/// <param name="reason"></param>
void Close(String? reason);
}
/// <summary>轻量级应用主机</summary>
/// <remarks>
/// 文档 https://newlifex.com/core/host
/// 销毁主机时,会触发所有服务的停止事件
/// </remarks>
public class Host : DisposeBase, IHost
{
#region 属性
/// <summary>服务提供者</summary>
public IServiceProvider ServiceProvider { get; set; }
//private readonly IList<Type> _serviceTypes = new List<Type>();
/// <summary>服务集合</summary>
public IList<IHostedService> Services { get; } = new List<IHostedService>();
#endregion
#region 构造
static Host()
{
AppDomain.CurrentDomain.ProcessExit += OnExit;
Console.CancelKeyPress += OnExit;
#if NETCOREAPP
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx => OnExit(ctx, EventArgs.Empty);
#endif
#if NET6_0_OR_GREATER
PosixSignalRegistration.Create(PosixSignal.SIGINT, ctx => OnExit(ctx, EventArgs.Empty));
PosixSignalRegistration.Create(PosixSignal.SIGQUIT, ctx => OnExit(ctx, EventArgs.Empty));
PosixSignalRegistration.Create(PosixSignal.SIGTERM, ctx => OnExit(ctx, EventArgs.Empty));
#endif
}
/// <summary>通过制定服务提供者来实例化一个应用主机</summary>
/// <param name="serviceProvider"></param>
public Host(IServiceProvider serviceProvider) => ServiceProvider = serviceProvider;
/// <summary>销毁</summary>
/// <param name="disposing"></param>
protected override void Dispose(Boolean disposing)
{
base.Dispose(disposing);
//_life?.TrySetResult(0);
Close(disposing ? "Dispose" : "GC");
}
#endregion
#region 服务集合
/// <summary>添加服务</summary>
/// <typeparam name="TService"></typeparam>
public void Add<TService>() where TService : class, IHostedService
{
//var type = typeof(TService);
//_serviceTypes.Add(type);
// 把服务类型注册到容器中,以便后续获取
var ioc = (ServiceProvider as ServiceProvider)?.Container ?? ObjectContainer.Current;
//ioc.TryAddTransient(type, type);
ioc.AddHostedService<TService>();
}
/// <summary>添加服务</summary>
/// <param name="service"></param>
public void Add(IHostedService service) => Services.Add(service);
#endregion
#region 开始停止
/// <summary>开始</summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task StartAsync(CancellationToken cancellationToken)
{
// 从容器中获取所有服务。此时服务是倒序,需要反转
var svcs = new List<IHostedService>();
foreach (var item in ServiceProvider.GetServices<IHostedService>())
{
svcs.Add(item);
}
svcs.Reverse();
foreach (var item in svcs)
{
Services.Add(item);
}
//// 从容器中获取所有服务
//foreach (var item in _serviceTypes)
//{
// if (ServiceProvider.GetService(item) is IHostedService service) Services.Add(service);
//}
// 开始所有服务,任意服务出错都导致启动失败
foreach (var item in Services)
{
await item.StartAsync(cancellationToken).ConfigureAwait(false);
}
}
/// <summary>停止</summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task StopAsync(CancellationToken cancellationToken)
{
foreach (var item in Services)
{
try
{
await item.StopAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
XTrace.WriteException(ex);
}
}
}
#endregion
#region 运行大循环
private TaskCompletionSource<Object>? _life;
/// <summary>同步运行,大循环阻塞</summary>
public void Run() => RunAsync().GetAwaiter().GetResult();
/// <summary>异步允许,大循环阻塞</summary>
/// <returns></returns>
public async Task RunAsync()
{
XTrace.WriteLine("Starting......");
using var source = new CancellationTokenSource();
_life = new TaskCompletionSource<Object>();
RegisterExit((s, e) => Close(s?.GetType().Name));
await StartAsync(source.Token);
XTrace.WriteLine("Application started. Press Ctrl+C to shut down.");
await _life.Task;
XTrace.WriteLine("Application is shutting down...");
await StopAsync(source.Token);
XTrace.WriteLine("Stopped!");
}
/// <summary>关闭主机</summary>
/// <param name="reason"></param>
public void Close(String? reason)
{
XTrace.WriteLine("Application closed. {0}", reason);
_life?.TrySetResult(0);
}
#endregion
#region 退出事件
private static List<EventHandler> _events = new();
private static List<Action> _events2 = new();
private static Int32 _exited;
/// <summary>注册应用退出事件</summary>
/// <remarks>在不同场景可能被多次执行,调用方需要做判断</remarks>
/// <param name="onExit">回调函数</param>
public static void RegisterExit(EventHandler onExit) => _events.Add(onExit);
/// <summary>注册应用退出事件。仅执行一次</summary>
/// <param name="onExit">回调函数</param>
public static void RegisterExit(Action onExit) => _events2.Add(onExit);
private static void OnExit(Object? sender, EventArgs e)
{
foreach (var item in _events)
{
try
{
item(sender, e);
}
catch (Exception ex)
{
XTrace.WriteException(ex);
}
}
// 只执行一次
if (Interlocked.Increment(ref _exited) > 1) return;
foreach (var item in _events2)
{
try
{
item();
}
catch (Exception ex)
{
XTrace.WriteException(ex);
}
}
}
#endregion
}
/// <summary>后台任务</summary>
/// <remarks>
/// 文档 https://newlifex.com/core/host
/// </remarks>
public abstract class BackgroundService : IHostedService, IDisposable
{
private Task? _executingTask;
private CancellationTokenSource? _stoppingCts;
/// <summary>执行</summary>
/// <param name="stoppingToken"></param>
/// <returns></returns>
protected abstract Task ExecuteAsync(CancellationToken stoppingToken);
/// <summary>开始</summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual Task StartAsync(CancellationToken cancellationToken)
{
_stoppingCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_executingTask = ExecuteAsync(_stoppingCts.Token);
#if NET45
return _executingTask.IsCompleted ? _executingTask : Task.FromResult(0);
#else
return _executingTask.IsCompleted ? _executingTask : Task.CompletedTask;
#endif
}
/// <summary>停止</summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
if (_executingTask != null)
{
try
{
_stoppingCts?.Cancel();
}
finally
{
await Task.WhenAny(_executingTask, Task.Delay(-1, cancellationToken)).ConfigureAwait(continueOnCapturedContext: false);
}
}
}
/// <summary>销毁</summary>
public virtual void Dispose() => _stoppingCts?.Cancel();
}