Asp.Net核心长期运行/后台任务 [英] Asp.Net core long running/background task

查看:134
本文介绍了Asp.Net核心长期运行/后台任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下正确的模式是否可以在Asp.Net Core中实现长期运行的后台工作?还是我应该将 Task.Run / TaskFactory.StartNew TaskCreationOptions一起使用。 LongRunning 选项?

Is the following a correct pattern to implement long running background work in Asp.Net Core? Or should I be using some form of Task.Run/TaskFactory.StartNew with TaskCreationOptions.LongRunning option?

    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
        }
    }


推荐答案


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

Is the following a correct pattern to implement long running background work in Asp.Net Core?

是的,是在ASP.NET Core上开始长期运行的基本方法。您当然应该使用 Task.Run / StartNew / LongRunning -这种方法总是错误的。

Yes, this is the basic approach to start long-running work on ASP.NET Core. You should certainly not use Task.Run/StartNew/LongRunning - that approach has always been wrong.

请注意,您长时间运行的工作可能会在任何时候,这都是正常的。如果您需要更可靠的解决方案,那么您应该在ASP.NET之外有一个单独的后台系统(例如Azure函数/ AWS Lambda)。还有像Hangfire这样的库,可以给您一些可靠性,但也有其缺点。

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 (e.g., Azure functions / AWS lambdas). There are also libraries like Hangfire that give you some reliability but have their own drawbacks.

这篇关于Asp.Net核心长期运行/后台任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆