Start Background Task using ASP.Net Core Middleware

James B

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?}");
            });

}

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?

Stephen Cleary

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Asp.Net core long running/background task

User session in background task in ASP.NET Core

ASP.NET Core middleware or OWIN middleware?

Modify response using middleware in ASP.NET Core 3

asp.net core 2 web api task run background task

ASP.Net Core Background Service with Task Queue, does it need a Task.Delay?

Using .NET Core Session in middleware

Using ASP.NET Core middleware in ASP.NET 4.x app

Using Task.Run in ASP.Net Core

How to upload files using Asp .net core in background process

asp net core Middleware that needs apiversioning version

ASP.NET Core Middleware and URL Parsing

asp.net core middleware not redirecting

asp.net core middleware vs filters

ASP.NET Core 2.0 authentication middleware

Replace activator for middleware in ASP.NET Core

Async progress in ASP .NET Core middleware?

asp.net core route specific middleware

ASP.NET core Authorization Middleware

Running background task on demand in asp.net core 3.x

How to create a background task in startup service in asp.net core 1.0 Web API?

Mysterious Behavior of .NET Core Background Task

Short running background task in .NET Core

Google Cloud Background Task with .Net Core

Where am I supposed to start persistent background tasks in ASP.NET Core?

How do I start a background job at end of request on ASP.NET Core?

Asp.Net Core Web app: Global exception handling using IExceptionFilter vs custom middleware

Inject a script reference in HTML files using ASP.NET Core middleware

How can I return a response in ASP.NET Core MVC middleware using MVC's content negotiation?