使用ASP.Net Core中间件启动后台任务 [英] Start Background Task using ASP.Net Core Middleware

查看:393
本文介绍了使用ASP.Net Core中间件启动后台任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.Net Core中加载页面时,我正在尝试运行异步任务,即,我希望任务在用户路由到页面后立即运行,但要在任务执行之前显示该页面完全的.似乎使用ASP.Net内核,您可以使用中间件执行此类任务.所以我尝试将以下内容添加到Startup.cs

I'm attempting to run an asynchronous task when loading a page in ASP.Net Core, i.e., I want the task to run as soon as the user routes to the page but for the page to be displayed before the task has completed. It seems that with ASP.Net core you use middleware to perform such tasks. So I attempted to add the following to Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
        {

// Other configurations here
app.Use(async (context, next) =>
            {
                if (context.Request.Path.Value.Contains("PageWithAsyncTask"))
                {
                    var serviceWithAsyncTask = serviceProvider.GetService<IMyService>();
                    await serviceWithAsyncTask .DoAsync();
                }
                await next.Invoke();
            });

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

}

上述问题是由于DoAsync完成之前我们不调用next.Invoke(),因此页面加载有一定的延迟,直到DoAsync完成为止.如何正确实现上述内容,以便在运行DoAsync之后立即调用next.Invoke()?

The problem with the above is that there is a delay in the page loading until DoAsync has complete since we don't call next.Invoke() until DoAsync is complete. How do I correctly implement the above such that next.Invoke() is called immediately after I've got DoAsync running?

推荐答案

ASP.NET并非为后台任务而设计.我强烈建议使用适当的体系结构,例如Azure Functions/WebJobs/Worker Roles/Win32 services/等,并带有可靠的队列(Azure队列/MSMQ/等),以便ASP.NET应用程序可以进行交谈为其服务.

ASP.NET was not designed for background tasks. I strongly recommend using a proper architecture, such as Azure Functions / WebJobs / Worker Roles / Win32 services / etc, with a reliable queue (Azure queues / MSMQ / etc) for the ASP.NET app to talk to its service.

但是,如果您真的想要-并且愿意承担风险(特别是您的工作可能会中止),则可以使用

However, if you really want to - and are willing to accept the risks (specifically, that your work may be aborted), then you can use IApplicationLifetime.

这篇关于使用ASP.Net Core中间件启动后台任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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