我尝试在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()
,因此页面加载会有延迟。我该如何正确实现上述方法,以便在启动 DoAsync
后立即调用 next.Invoke()
?
IApplicationLifetime
的替代方案。 - Stephen Cleary