IHostedService的多种实现 [英] Multiple Implementations of IHostedService

查看:90
本文介绍了IHostedService的多种实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用IHostedService创建后台服务.如果我只有一个后台服务,一切都会正常.当我尝试创建 IHostedService 的多个实现时,只有第一个注册的实际运行.

I'm trying to create background services using IHostedService. Everything works fine if I only have ONE background service. When I try to create more than one implementation of IHostedService only the one that was registered first actually runs.

services.AddSingleton<IHostedService, HostedServiceOne>();
services.AddSingleton<IHostedService, HostedServiceTwo>();

在上面的示例中,调用了 HostedServiceOne 上的 StartAsync ,但是从未调用过 HostedServiceTwo 上的 StartAsync .如果我交换注册 IHostedService 的两个实现的顺序(在 IHostedServiceOne 之前放入 IHostedServiceTwo ),则在 StartAsync code> HostedServiceTwo 被调用,但从未为 HostedServiceOne 调用.

In the above sample StartAsync on HostedServiceOne gets called but StartAsync on HostedServiceTwo never gets called. If I swap the order of registering the two implementations of IHostedService (put IHostedServiceTwo before IHostedServiceOne) then StartAsync on HostedServiceTwo gets called but never for HostedServiceOne.

我被引导至以下位置:

如何注册

但是,这不适用于 IHostedService .要使用建议的方法,我将不得不调用 serviceProvider.GetServices< IService>(); ,但是似乎 IHostedService.StartAsync 似乎在内部被调用.我什至不知道该在何处触发 IHostedService.StartAsync .

However this isn't for IHostedService. To use the suggested approach I would have to make a call to serviceProvider.GetServices<IService>(); but it seems that IHostedService.StartAsync seems to be called internally. I'm not even sure where I would call that to trigger IHostedService.StartAsync.

推荐答案

我遇到了同样的问题.必须在每个服务中返回Task.CompletedTask;

I had the same problem. It was necessary to return Task.CompletedTask in each services;

public class MyHostedService: IHostedService
{
    public Task StartAsync(CancellationToken cancellationToken)
    {
        Task.Run(() => SomeInfinityProcess(cancellationToken));
        return Task.CompletedTask;
    }

    public void SomeInfinityProcess(CancellationToken cancellationToken)
    {
        for (; ; )
        {
            Thread.Sleep(1000);
            if (cancellationToken.IsCancellationRequested)
                break;
        }
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}

Startup.cs是相同的:

Startup.cs is same:

    services.AddHostedService<MyHostedService>();
    services.AddHostedService<MyHostedService2>();
    ...

这篇关于IHostedService的多种实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆