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

时间:2017-07-10 13:14:31

标签: c# asp.net-core .net-core

以下是在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
        }
    }

2 个答案:

答案 0 :(得分:18)

  

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

是的,这是启动ASP.NET Core长期运行工作的基本方法。您当然使用24, 79, 81, 2, 1, 60, cnt: 5 / Task.Run / StartNew - 该方法总是错误。

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

答案 1 :(得分: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.
    //.....
}
相关问题