.NET CORE 3.1.1--HostingAbstractionsHostExtensions 类源码

 1 // Assembly location: C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App\3.1.1\Microsoft.Extensions.Hosting.Abstractions.dll
 2 
 3 using Microsoft.Extensions.DependencyInjection;
 4 using System;
 5 using System.Threading;
 6 using System.Threading.Tasks;
 7 
 8 namespace Microsoft.Extensions.Hosting
 9 {
10   public static class HostingAbstractionsHostExtensions
11   {
12     public static void Start(this IHost host)
13     {
14       host.StartAsync(new CancellationToken()).GetAwaiter().GetResult();
15     }
16 
17     public static Task StopAsync(this IHost host, TimeSpan timeout)
18     {
19       return host.StopAsync(new CancellationTokenSource(timeout).Token);
20     }
21 
22     public static void WaitForShutdown(this IHost host)
23     {
24       host.WaitForShutdownAsync(new CancellationToken()).GetAwaiter().GetResult();
25     }
26 
27     public static void Run(this IHost host)
28     {
29       host.RunAsync(new CancellationToken()).GetAwaiter().GetResult();
30     }
31 
32     public static async Task RunAsync(this IHost host, CancellationToken token = default (CancellationToken))
33     {
34       try
35       {
36         await host.StartAsync(token);
37         await host.WaitForShutdownAsync(token);
38       }
39       finally
40       {
41         if (host is IAsyncDisposable asyncDisposable)
42           await asyncDisposable.DisposeAsync();
43         else
44           host.Dispose();
45       }
46     }
47 
48     public static async Task WaitForShutdownAsync(this IHost host, CancellationToken token = default (CancellationToken))
49     {
50       IHostApplicationLifetime service = host.Services.GetService<IHostApplicationLifetime>();
51       token.Register((Action<object>) (state => ((IHostApplicationLifetime) state).StopApplication()), (object) service);
52       TaskCompletionSource<object> completionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
53       service.ApplicationStopping.Register((Action<object>) (obj => ((TaskCompletionSource<object>) obj).TrySetResult((object) null)), (object) completionSource);
54       object task = await completionSource.Task;
55       await host.StopAsync(new CancellationToken());
56     }
57   }
58 }

 

posted @ 2020-03-09 13:58  NiKaFace  阅读(676)  评论(0编辑  收藏  举报