Start Background Task using ASP.Net Core Middleware
In ASP.NET Core 2 the IHostedService is designed to run your background tasks. Register the IHostedService as Singleton and it is automatically started at startup:
implementing-background-tasks-in-microservices-with-ihostedservice-and-the-backgroundservice-class-net-core-2-x
asp-net-core-background-processing
Since Asp.Net core 2.1 to use background tasks it is very convenient to implement IHostedService
by deriving from the BackgroundService
base class. Here is the sample taken from here:
public class MyServiceA : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine("MyServiceA is starting.");
stoppingToken.Register(() => Console.WriteLine("MyServiceA is stopping."));
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine("MyServiceA is doing background work.");
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
Console.WriteLine("MyServiceA background task is stopping.");
}
}
Then just register it in Startup.ConfigureServices
:
services.AddSingleton<IHostedService, MyServiceA>();
And as Stephen Cleary noted Asp.Net
application may not be the best place for background tasks (e.g. when app is hosted in IIS it can be shut down because of app pool recycles), but for some scenarios it can be applied very well.
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
.