承载系统
2022-06-15 09:36 qgbo 阅读(172) 评论(0) 编辑 收藏 举报.netcore 最简单的承载系统,代码如下。
1 public class Test : IHostedService 2 { 3 public Task StartAsync(CancellationToken cancellationToken) 4 { 5 Console.WriteLine("StartAsync:"+ Thread.CurrentThread.ManagedThreadId); 6 return Task.CompletedTask; 7 } 8 9 public Task StopAsync(CancellationToken cancellationToken) 10 { 11 Console.WriteLine("End"); 12 return Task.CompletedTask; 13 } 14 } 15 16 public class Program 17 { 18 public static void Main(string[] args) 19 { 20 // CreateHostBuilder(args).Build().Run(); 21 Console.WriteLine("qqqqqq:" + Thread.CurrentThread.ManagedThreadId); 22 var builder =new HostBuilder(); 23 builder.ConfigureServices(services => 24 { 25 services.AddHostedService<Test>(); 26 }); 27 28 var host=builder.Build(); 29 host.Run(); 30 Console.WriteLine("qqqqq333q:" + Thread.CurrentThread.ManagedThreadId); 31 }
1. new HostBuilder(), 这里面有
private List<Action<HostBuilderContext, IServiceCollection>> _configureServicesActions = new List<Action<HostBuilderContext, IServiceCollection>>();
执行 builder.ConfigureServices() 这个方法里的委托放进这个集合来。还有几个类似的集合,类似的作用。
在28 行build 的时候,会把这个委托的集合执行一遍。
2.这里面还有 private IServiceProvider? _appServices;
这也是Build 的时候, new ServiceCollection(); 然后把 这个 集合 转为 serviceProvider
从这里依赖注入开始,并 注入了 IHost
Build 的最后把这个 Ihost 返回。
最后Host run .
会把 容器里的 IHostedService 都取出来,并执行Start,然后 等待。直到 Lifttime 通知程序退出。
最后,容器里的 IHostedService 都取出来,并执行Stop。
如果是 backgroudservice, 他的start 如下:第7行,没有await, 这会启动线程。
1 public virtual Task StartAsync(CancellationToken cancellationToken) 2 { 3 // Create linked token to allow cancelling executing task from provided token 4 _stoppingCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); 5 6 // Store the task we're executing 7 _executeTask = ExecuteAsync(_stoppingCts.Token); 8 9 // If the task is completed then return it, this will bubble cancellation and failure to the caller 10 if (_executeTask.IsCompleted) 11 { 12 return _executeTask; 13 } 14 15 // Otherwise it's running 16 return Task.CompletedTask; 17 }
3. 这里有 UseServiceProviderFactory(),这个方法,可以替换DI容器,比如autofac.
4. private void InitializeAppConfiguration(), 这个方法,初始化了 AppConfiguration, 加入了 第一个配置 :ChainedConfigurationSource, 而这个配置的内容,就是 HostConfigration
5. 上面的代码 改为 网站:
var webHostBuilderOptions = new WebHostBuilderOptions();
WebHost.ConfigureWebDefaults(webHostBuilder);
var webhostBuilder = new GenericWebHostBuilder(builder, webHostBuilderOptions);
webhostBuilder.UseStartup<StartUp>();
builder.ConfigureServices((context, services) => services.AddHostedService<GenericWebHostService>());
第二行的方法,里面注入了 kestrel(Iserver).
最后一行的 GenericWebHostService 引用了 Iserver