应用程序停止时停止服务的顺序是什么

iva*_*f81 1 c# .net-core asp.net-core

我有很多服务托管应用程序。它包含ServiceAServiceB。他们用以下方法主持AddHostedService

var hostBuilder = new HostBuilder()
    .ConfigureServices((hostContext, services) =>
    {
         services.AddHostedService<ServiceA>();
         services.AddHostedService<ServiceB>();
    });

using (var host = hostBuilder.Build())
{
    host.Start();
    host.WaitForShutdown();
}
Run Code Online (Sandbox Code Playgroud)

ServiceB我知道ServiceA 启动后将运行什么。停止服务的顺序是什么?ServiceA停车后能保证停车吗ServiceB

Kir*_*kin 5

的实现按照添加顺序开始(IHostedService来源

_hostedServices = Services.GetService<IEnumerable<IHostedService>>();

foreach (var hostedService in _hostedServices)
{
    // Fire IHostedService.Start
    await hostedService.StartAsync(cancellationToken).ConfigureAwait(false);
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中,从 DI 容器中Services.GetService<IEnumerable<IHostedService>>()检索 的所有实现IHostedService,作为IEnumerable<T>. 这些是按注册时排序的。

的实现以相反的顺序停止IHostedService(来源

foreach (var hostedService in _hostedServices.Reverse())
{
    // ...

    await hostedService.StopAsync(token).ConfigureAwait(false);

    // ...
}
Run Code Online (Sandbox Code Playgroud)

在您的示例场景中,ServiceA将在 之前开始ServiceB,但会在 之后停止 ServiceB