这就应证了开头所说的:通用主机的目标是将HTTP管道从Web Host中脱离出来,使得Asp.Net Core的那套东西也适用于其他.Net Core程序。
如何使用? Run函数解读我觉得要知道怎么用,那么我们就首先要知道Host的Run方法内到底是在执行什么?
所以我们深入源码,一路F12!
builder.RunConsoleAsync(); =>hostBuilder.UseConsoleLifetime().Build().RunAsync(cancellationToken);=> await host.StartAsync(token);
总算找到了,最关键的在这里。
public async Task StartAsync(CancellationToken cancellationToken = default (CancellationToken)) { this._logger.Starting(); TaskCompletionSource<object> completionSource1 = new TaskCompletionSource<object>(); ref CancellationToken local = ref cancellationToken; TaskCompletionSource<object> completionSource2 = completionSource1; local.Register((Action<object>) (obj => ((TaskCompletionSource<object>) obj).TrySetCanceled()), (object) completionSource2); IHostLifetime hostLifetime1 = this._hostLifetime; TaskCompletionSource<object> completionSource3 = completionSource1; hostLifetime1.RegisterDelayStartCallback((Action<object>) (obj => ((TaskCompletionSource<object>) obj).TrySetResult((object) null)), (object) completionSource3); IHostLifetime hostLifetime2 = this._hostLifetime; ApplicationLifetime applicationLifetime = this._applicationLifetime; hostLifetime2.RegisterStopCallback((Action<object>) (obj => (obj as IApplicationLifetime)?.StopApplication()), (object) applicationLifetime); object task = await completionSource1.Task; this._hostedServices = this.Services.GetService<IEnumerable<IHostedService>>(); foreach (IHostedService hostedService in this._hostedServices) await hostedService.StartAsync(cancellationToken).ConfigureAwait(false ); this._applicationLifetime?.NotifyStarted(); this._logger.Started(); }