.NET 8 的 IHostedLifecycleService 接口是鸡肋功能吗?

开发 前端
IHostedLifecycleService​是.NET 8中引入的一个新特性,它可以让我们在使用多个IHostedService实现的时候,更加灵活和高效地控制它们的启动和停止,避免出现不必要的依赖和冲突。

.NET 8 引入了一个新的接口,叫做IHostedLifecycleService,这个接口继承自现有的 IHostedService 接口,它为 BackgroundService 提供了一些新的生命周期事件的方法:

  • StartingAsync:在 StartAsync 方法之前执行,用于执行一些初始化或预处理的逻辑。
  • StartedAsync:在 StartAsync 方法之后执行,用于执行一些后处理或检查的逻辑。
  • StoppingAsync:在 StopAsync 方法之前执行,用于执行一些清理或释放的逻辑。
  • StoppedAsync:在 StopAsync 方法之后执行,用于执行一些收尾或报告的逻辑。

这些方法都发生在现有的 StartAsync 和 StopAsync 方法之前或之后。

示例代码

下面的示例演示如何使用新 API:

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<MyIOWorker>();

var host = builder.Build();
host.Run();

public class MyIOWorker : BackgroundService, IHostedLifecycleService
{
    public async Task StartingAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine($"{nameof(MyIOWorker)} Starting");//业务逻辑
    }
    public async Task StartedAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine($"{nameof(MyIOWorker)} Started");//业务逻辑
    }
    public async Task StoppingAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine($"{nameof(MyIOWorker)} Stopping");//业务逻辑
    }
    public async Task StoppedAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine($"{nameof(MyIOWorker)} Stopped");//业务逻辑
    }
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            Console.WriteLine($"{nameof(MyIOWorker)} Execute");//业务逻辑
            await Task.Delay(1000, stoppingToken);
        }
    }
}

输出结果如下:

MyIOService Starting
MyIOService Execute
MyIOService Started

...

MyIOService Stopping
MyIOService Stopped

鸡肋功能?

但是,直接使用 IHostedService 接口一样可以实现相同功能:

public class MyIOWorker : BackgroundService
{ 
    public override async Task StartAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine($"{nameof(MyIOWorker)} Starting");//业务逻辑
        await base.StartAsync(cancellationToken);
        Console.WriteLine($"{nameof(MyIOWorker)} Started");//业务逻辑
    }
     
    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine($"{nameof(MyIOWorker)} Stopping");//业务逻辑
        await base.StopAsync(cancellationToken);
        Console.WriteLine($"{nameof(MyIOWorker)} Stopped");//业务逻辑
    }
    
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            Console.WriteLine($"{nameof(MyIOWorker)} ExecuteAsync");//业务逻辑
            await Task.Delay(1000, stoppingToken);
        }
    }
}

那么,新特性IHostedLifecycleService的意义何在呢?

仅仅为了,方便放置不同逻辑的代码吗?

探究源码

在dotnet/runtime源码https://github.com/dotnet/runtime/blob/main/src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs中,我们找到了 IHostedLifecycleService 的使用逻辑:

// Call StartingAsync().
if (_hostedLifecycleServices is not null)
{
    await ForeachService(_hostedLifecycleServices, cancellationToken, concurrent, abortOnFirstException, exceptions,
        (service, token) => service.StartingAsync(token)).ConfigureAwait(false);

    // Exceptions in StartingAsync cause startup to be aborted.
    LogAndRethrow();
}

// Call StartAsync().
await ForeachService(_hostedServices, cancellationToken, concurrent, abortOnFirstException, exceptions,
    async (service, token) =>
    {
        await service.StartAsync(token).ConfigureAwait(false);

        if (service is BackgroundService backgroundService)
        {
            _ = TryExecuteBackgroundServiceAsync(backgroundService);
        }
    }).ConfigureAwait(false);

// Exceptions in StartAsync cause startup to be aborted.
LogAndRethrow();

// Call StartedAsync().
if (_hostedLifecycleServices is not null)
{
    await ForeachService(_hostedLifecycleServices, cancellationToken, concurrent, abortOnFirstException, exceptions,
        (service, token) => service.StartedAsync(token)).ConfigureAwait(false);
}

上面的代码先遍历执行IEnumerable<IHostedLifecycleService>? _hostedLifecycleServices的StartingAsync方法,再遍历执行IEnumerable<IHostedService>? _hostedServices的StartAsync方法。

也就是说,如果存在多个IHostedLifecycleService实现,我们可以把初始化代码放在StartingAsync方法实现中,保证了全部初始化逻辑执行成功后才会执行StartAsync方法中正式的业务逻辑。对于StopAsync方法也是同理。

使用场景

比如,如果直接使用 IHostedService 接口:

builder.Services.AddHostedService<AWorker>();
builder.Services.AddHostedService<BWorker>();

public class AWorker : BackgroundService
{ 
    public override async Task StartAsync(CancellationToken cancellationToken)
    {
        //初始化数据库A表
    } 
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        //访问数据库A表和B表
    }
}

public class BWorker : BackgroundService
{ 
    public override async Task StartAsync(CancellationToken cancellationToken)
    {
        //初始化数据库B表
    } 
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        //访问数据库A表和B表
    }
}

由于执行有先后顺序,初始化数据库B表操作还没有执行,AWorker 就已经开始执行ExecuteAsync方法了,AWorker 的访问数据库A表和B表操作可能产生不可预料的结果。

现在使用IHostedLifecycleService,将初始化放在生命周期的早期:

public class AWorker : BackgroundService, IHostedLifecycleService
{
    public async Task StartingAsync(CancellationToken cancellationToken)
    {
        //初始化数据库A表
    } 
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        //访问数据库A表和B表
    }
}

public class BWorker : BackgroundService, IHostedLifecycleService
{
    public async Task StartingAsync(CancellationToken cancellationToken)
    {
        //初始化数据库B表
    } 
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        //访问数据库A表和B表
    }
}

现在,访问数据库A表和B表操作可以保证正常执行了。

默认情况下,多个IHostedLifecycleService实现是按顺序执行的,我们还可以设置它们并发启动和停止,节约整体启动时间:

builder.Services.Configure<HostOptions>(options =>
{
    options.ServicesStartConcurrently = true;
    options.ServicesStopConcurrently = true;
});

总结

IHostedLifecycleService是.NET 8中引入的一个新特性,它可以让我们在使用多个IHostedService实现的时候,更加灵活和高效地控制它们的启动和停止,避免出现不必要的依赖和冲突。

责任编辑:武晓燕 来源: MyIO
相关推荐

2009-08-14 15:42:11

什么是.NET接口.NET抽象类

2021-03-22 17:00:15

区块链NFT数字资产

2020-10-23 14:18:00

智慧社区互联网科技

2011-11-17 14:05:47

笔记本常见问题

2017-09-13 16:46:38

敏捷站会团队

2023-04-14 07:49:26

iOS安卓

2022-12-15 16:13:19

Windows11微软

2023-07-09 23:55:16

C++RoslynILC

2015-09-18 09:49:50

3DTouch苹果

2017-07-26 08:17:03

V4AppLaunchChApi

2021-08-28 06:03:42

5G 5G网络5G商用

2018-07-10 10:09:49

轻应用Facebook开发者

2016-02-15 09:51:53

2024-02-22 09:21:09

.NETActionOptions

2013-09-05 11:18:58

.NetWeb

2021-11-28 06:37:12

Windows11系统小组件系统

2022-08-17 16:38:46

WLAN接口组件功能

2015-11-03 13:27:32

中国软件网

2009-02-13 09:26:43

心态职场工作

2009-12-28 10:04:59

.NET 4.0数组
点赞
收藏

51CTO技术栈公众号