简体   繁体   English

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

[英]Asp.Net core long running/background task

Is the following a correct pattern to implement long running background work in Asp.Net Core?以下是在 Asp.Net Core 中实现长时间运行的后台工作的正确模式吗? Or should I be using some form of Task.Run / TaskFactory.StartNew with TaskCreationOptions.LongRunning option?或者我应该使用某种形式的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
        }
    }

Check also .NET Core 2.0 IHostedService .另请检查 .NET Core 2.0 IHostedService Here is the documentation .这是文档 From .NET Core 2.1 we will have BackgroundService abstract class.从 .NET Core 2.1 开始,我们将拥有BackgroundService抽象类。 It can be used like this:它可以像这样使用:

public class UpdateBackgroundService: BackgroundService
{
    private readonly DbContext _context;

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

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

In your startup you just have to register class:在您的启动中,您只需要注册类:

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

Is the following a correct pattern to implement long running background work in Asp.Net Core?以下是在 Asp.Net Core 中实现长时间运行的后台工作的正确模式吗?

Yes, this is the basic approach to start long-running work on ASP.NET Core.是的,这是在 ASP.NET Core 上开始长时间运行工作的基本方法。 You should certainly not use Task.Run / StartNew / LongRunning - that approach has always been wrong.您当然应该使用Task.Run / StartNew / LongRunning - 这种方法一直是错误的。

Note that your long-running work may be shut down at any time, and that's normal.请注意,您长时间运行的工作可能会随时关闭,这很正常。 If you need a more reliable solution, then you should have a separate background system outside of ASP.NET (eg, Azure functions / AWS lambdas).如果您需要更可靠的解决方案,那么您应该在 ASP.NET 之外拥有一个单独的后台系统(例如,Azure 函数/AWS lambdas)。 There are also libraries like Hangfire that give you some reliability but have their own drawbacks.还有像 Hangfire 这样的库可以为您提供一些可靠性,但也有自己的缺点。

Update: I've written a blog series on how to implement the more reliable approach , using a durable queue with a separate background system.更新:我写了一个关于如何实现更可靠方法的博客系列,使用具有单独后台系统的持久队列。 In my experience, most developers need the more reliable approach because they don't want their long-running work to be lost.根据我的经验,大多数开发人员需要更可靠的方法,因为他们不希望长时间运行的工作丢失。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM