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

ubi*_*ubi 18 c# .net-core asp.net-core

以下是在Asp.Net Core中实现长时间运行后台工作的正确模式吗?或者我应该使用某种形式的Task.Run/ TaskFactory.StartNewwith TaskCreationOptions.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
        }
    }
Run Code Online (Sandbox Code Playgroud)

Mak*_*kla 19

另请参阅.NET Core 2.0 IHostedService.这是文档.从.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 ...
    }
}
Run Code Online (Sandbox Code Playgroud)

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

public static IServiceProvider Build(IServiceCollection services)
{
    //.....
    services.AddSingleton<IHostedService, UpdateBackgroundService>();
    services.AddTransient<IHostedService, UpdateBackgroundService>();  //For run at startup and die.
    //.....
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*ary 18

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

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

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

  • @ubi:ASP.NET偶尔会回收以保持干净.通常的原因还有:操作系统更新,移动云编排,断电等. (3认同)