使用ASP.Net Core中间件启动后台任务

编程入门 行业动态 更新时间:2024-10-24 14:17:23
本文介绍了使用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.

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

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中间件启动后台任务

本文发布于:2023-11-05 09:51:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560521.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中间件   后台   ASP   Net   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!