我试图在 ASP.Net Core 中加载页面时运行异步任务,即,我希望任务在用户路由到页面后立即运行,但要在任务完成之前显示页面。看起来,使用 ASP.Net core,您可以使用中间件来执行此类任务。所以我尝试添加以下内容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()
until DoAsync
做完了。我如何正确实施上述内容,以便next.Invoke()
我得到后立即被调用DoAsync
跑步?
在 ASP.NET Core 2 中,IHostedService 旨在运行后台任务。
将 IHostedService 注册为 Singleton,启动时自动启动:
使用 ihostedservice 和 backgroundservice-class-net-core-2-x 实现微服务中的后台任务 https://blogs.msdn.microsoft.com/cesardelatorre/2017/11/18/implementing-background-tasks-in-microservices-with-ihostedservice-and-the-backgroundservice-class-net-core-2-x/
asp-net-core-后台处理 https://thinkrethink.net/2018/02/21/asp-net-core-background-processing/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)