简体   繁体   English

如何在 .net core 3.0 中并行运行多个 BackgroundService?

[英]How to run multiple BackgroundService parallel in .net core 3.0?

How is it possible to run multiple IHostedServices in parallel?如何并行运行多个 IHostedServices?

I use the WorkerService in.Net Core 3.0 and want both services to run parallel.我使用 WorkerService in.Net Core 3.0 并希望这两个服务并行运行。 Currently the second service is waiting for the first one to finish.目前,第二个服务正在等待第一个服务完成。 Both services should run endlessly.两种服务都应该无休止地运行。

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<ServiceA>();
                services.AddHostedService<ServiceB>();
            });
    }

A service looks like this:服务如下所示:

public class ServiceA : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        do
        {
            Console.WriteLine("Sample");
            await Task.Delay(5000, stoppingToken);
        } while (!stoppingToken.IsCancellationRequested);
    }
}

// edit: Very reluctantly I would use a Task.Run(() => method()); // 编辑:我很不情愿地使用Task.Run(() => method()); method like this.像这样的方法。 But of course this way always works:但当然,这种方式总是有效的:

public class ServiceA : BackgroundService
{
    public override Task StartAsync(CancellationToken cancellationToken)
    {
        Task.Factory.StartNew(() => ExecuteAsync(cancellationToken), cancellationToken);
        return Task.CompletedTask;
    }
}

I asked myself a similar question and made some search but couldn't find a good answer.我问了自己一个类似的问题并进行了一些搜索,但找不到一个好的答案。 I solved the issue running every background service in Task.Run with a cancellation token from BackgroundService.ExecuteAsync() I have 2 services like you.我使用来自BackgroundService.ExecuteAsync()的取消令牌解决了在Task.Run中运行每个后台服务的问题。我有 2 个像你这样的服务。

public class BackgroundService1: BackgroundService
{
    public BackgroundService1()
    {
    }
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Task.Run(async () =>
        {
            await DoWork(stoppingToken);
        }, stoppingToken);
        return Task.CompletedTask;
    }
}

//Second service is just like the first one: //第二次服务和第一次一样:

public class BackgroundService2: BackgroundService
{
    public BackgroundService2()
    {
    }
    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Task.Run(async () =>
        {
            await DoWork(stoppingToken);
        }, stoppingToken);
        return Task.CompletedTask;
    }
}

and register them in Program.cs并在 Program.cs 中注册它们

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<BackgroundService1>();
                services.AddHostedService<BackgroundService2>();
            })
            .UseWindowsService()

I've had the same kind of issue: Multiple service that do different work at different frequency.我遇到过同样的问题:多种服务以不同的频率完成不同的工作。

When looking into it BackgroundService seems to be designed for sequential execution (infinite loop based service's worst enemy).当研究它时,BackgroundService 似乎是为顺序执行而设计的(基于无限循环的服务的最大敌人)。

After getting a first hint from this thread, I found the solution that works for my case https://docs.microsoft.com/en-us/dotnet/core/extensions/timer-service从这个线程获得第一个提示后,我找到了适用于我的案例https://docs.microsoft.com/en-us/dotnet/core/extensions/timer-service的解决方案

The base TimerService implements IHostedService and IAsyncDisposable.基本 TimerService 实现 IHostedService 和 IAsyncDisposable。

  • StartAsync() starts the timer on the DoWork() StartAsync() 在 DoWork() 上启动计时器
  • DoWork() is your overridable main work procedure. DoWork() 是您可覆盖的主要工作程序。
  • StopAsync() stops the timer gracefully. StopAsync() 优雅地停止计时器。
  • DisposeAsync() cleans up. DisposeAsync() 清理。

I've Tested by deriving multiple TimerServices with different execution frequencies and adding them with services.AddHostedService<>();我已经通过派生具有不同执行频率的多个 TimerService 并使用 services.AddHostedService<>(); 添加它们进行了测试

They all start and run at the same time, do their bit on clock.他们都在同一时间开始和运行,按时完成。

/.\ It is not Task based as it uses timer events. /.\ 它不是基于任务的,因为它使用计时器事件。 Just saying because I've already had quite a difficult troubleshooting experience the one time I mixed time based events and Tasks /!\之所以这么说,是因为有一次我混合了基于时间的事件和任务 /!\

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 .Net Core 3.0每天午夜运行BackgroundService - Run BackgroundService every day at midnight in .Net Core 3.0 如何在 ASP.NET Core 2.1 中的计时器上运行 BackgroundService - How to run BackgroundService on a timer in ASP.NET Core 2.1 在 .net 核心 3.0 BackgroundService 应用程序中,为什么我的配置 object 作为服务运行时为空,而不是作为控制台应用程序运行? - In a .net core 3.0 BackgroundService app, why is my configuration object empty when running as service, but not as console app? 如何在 ASP.net 内核中手动取消 BackgroundService - How to cancel manually a BackgroundService in ASP.net core 如何手动重启 ASP.net 核心中的 BackgroundService - How to restart manually a BackgroundService in ASP.net core Windows 服务使用.net核心BackgroundService,如何优雅停止? - Windows Service using .net core BackgroundService, how to gracefully stop? 在 Net6 Worker 进程中使用 task.Run 并行两个后台服务可以吗? - Is it ok to use task.Run to parallel two backgroundservice in a Net6 Worker process? 多个 Worker 在 .NET 内核中并行运行 - Multiple Workers to run parallel-ly in .NET core 如何在多台服务器上发布 Web API net core 3.0 - How to Publish a Web API net core 3.0 in multiple servers 如何在 ASP.NET 核心应用程序中使用 BackgroundService 每年执行一个方法? - How can I execute a method every year using BackgroundService in ASP.NET core Application?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM