Asp.Net核心长期运行/后台任务

问题描述 投票:18回答:2

以下是在Asp.Net Core中实现长时间运行后台工作的正确模式吗?或者我应该使用某种形式的Task.Run / TaskFactory.StartNewTaskCreationOptions.LongRunning选项?

    public void Configure(IApplicationLifetime lifetime)
    {
        lifetime.ApplicationStarted.Register(() =>
        {
            // not awaiting the 'promise task' here
            var t = DoWorkAsync(lifetime.ApplicationStopping);

            lifetime.ApplicationStopped.Register(() =>
            {
                try
                {
                    // give extra time to complete before shutting down
                    t.Wait(TimeSpan.FromSeconds(10));
                }
                catch (Exception)
                {
                    // ignore
                }
            });
        });
    }

    async Task DoWorkAsync(CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            await // async method
        }
    }
c# asp.net-core .net-core
2个回答
18
投票

以下是在Asp.Net Core中实现长时间运行后台工作的正确模式吗?

是的,这是启动ASP.NET Core长期运行工作的基本方法。你当然不应该使用Task.Run / StartNew / LongRunning - 这种方法一直都是错误的。

请注意,您的长时间工作可能会随时关闭,这是正常的。如果您需要更可靠的解决方案,那么您应该在ASP.NET之外拥有一个单独的后台系统(例如,Azure functions / AWS lambdas)。还有像Hangfire这样的库可以提供一些可靠性,但也有其自身的缺点。


17
投票

另请参阅.NET Core 2.0 IHostedService。这是documentation。从.NET Core 2.1我们将有BackgroundService抽象类。它可以像这样使用:

public class UpdateBackgroundService: BackgroundService
{
    private readonly DbContext _context;

    public UpdateTranslatesBackgroundService(DbContext context)
    {
        this._context= context;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await ...
    }
}

在您的创业公司中,您只需注册课程:

public static IServiceProvider Build(IServiceCollection services)
{
    //.....
    services.AddSingleton<IHostedService, UpdateBackgroundService>();
    services.AddTransient<IHostedService, UpdateBackgroundService>();  //For run at startup and die.
    //.....
}
© www.soinside.com 2019 - 2024. All rights reserved.