In ASP.NET Core, background tasks can be implemented as hosted services. A hosted service is a class with background task logic that implements the IHostedService interface. This topic provides three hosted service examples:
Background task that runs on a timer.
Hosted service that activates a scoped service. The scoped service can use dependency injection (DI).
Queued background tasks that run sequentially.
IHostedService interface
The IHostedService interface defines two methods for objects that are managed by the host:
StartAsync(CancellationToken): StartAsync contains the logic to start the background task. StartAsync is called before:
The app’s request processing pipeline is configured (Startup.Configure).
The server is started and IApplicationLifetime.ApplicationStarted is triggered. The default behavior can be changed so that the hosted service’s StartAsync runs after the app’s pipeline has been configured and ApplicationStarted is called.
StopAsync(CancellationToken): Triggered when the host is performing a graceful shutdown. StopAsync contains the logic to end the background task. Implement IDisposable and finalizers (destructors) to dispose of any unmanaged resources.
The cancellation token has a default five second timeout to indicate that the shutdown process should no longer be graceful. When cancellation is requested on the token:
Any remaining background operations that the app is performing should be aborted.
Any methods called in StopAsync should return promptly.
However, tasks aren’t abandoned after cancellation is requested—the caller awaits all tasks to complete.
If the app shuts down unexpectedly, StopAsync might not be called. Therefore, any methods called or operations conducted in StopAsync might not occur.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
using Microsoft.Extensions.Hosting; using System.Threading; using System.Threading.Tasks;
publicclassSampleHostedService : IHostedService { public Task StartAsync(CancellationToken cancellationToken) { }
public Task StopAsync(CancellationToken cancellationToken) { } }
BackgroundService base class
BackgroundService is a base class for implementing a long running IHostedService.
ExecuteAsync(CancellationToken) is called to run the background service. The implementation returns a Task that represents the entire lifetime of the background service. No further services are started until ExecuteAsync becomes asynchronous, such as by calling await. Avoid performing long, blocking initialization work in ExecuteAsync. The host blocks in StopAsync(CancellationToken) waiting for ExecuteAsync to complete.
The cancellation token is triggered when IHostedService.StopAsync is called. Your implementation of ExecuteAsync should finish promptly when the cancellation token is fired in order to gracefully shut down the service. Otherwise, the service ungracefully shuts down at the shutdown timeout. For more information, see the IHostedService interface section.
1 2 3 4 5 6 7 8 9 10 11
using Microsoft.Extensions.Hosting; using System.Threading; using System.Threading.Tasks;
A timed background task makes use of the System.Threading.Timer class. The timer triggers the task’s DoWork method. The timer is disabled on StopAsync and disposed when the service container is disposed on Dispose:
public Task StartAsync(CancellationToken stoppingToken) { _logger.LogInformation("Timed Hosted Service running.");
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return Task.CompletedTask; }
privatevoidDoWork(object state) { var count = Interlocked.Increment(ref executionCount);
_logger.LogInformation( "Timed Hosted Service is working. Count: {Count}", count); }
public Task StopAsync(CancellationToken stoppingToken) { _logger.LogInformation("Timed Hosted Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask; }
publicvoidDispose() { _timer?.Dispose(); } } }
The Timer doesn’t wait for previous executions of DoWork to finish, so the approach shown might not be suitable for every scenario. Interlocked.Increment is used to increment the execution counter as an atomic operation, which ensures that multiple threads don’t update executionCount concurrently.
To use scoped services within a BackgroundService, create a scope. No scope is created for a hosted service by default.
The scoped background task service contains the background task’s logic. In the following example:
The service is asynchronous. The DoWork method returns a Task. For demonstration purposes, a delay of ten seconds is awaited in the DoWork method. An ILogger is injected into the service.
publicasync Task DoWork(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { executionCount++;
_logger.LogInformation( "Scoped Processing Service is working. Count: {Count}", executionCount);
await Task.Delay(10000, stoppingToken); } } }
The hosted service creates a scope to resolve the scoped background task service to call its DoWork method. DoWork returns a Task, which is awaited in ExecuteAsync:
publicoverrideasync Task StopAsync(CancellationToken stoppingToken) { _logger.LogInformation( "Consume Scoped Service Hosted Service is stopping.");
awaitbase.StopAsync(stoppingToken); } }
The services are registered in IHostBuilder.ConfigureServices (Program.cs). The hosted service is registered with the AddHostedService extension method:
1 2 3 4 5 6
// Program.IHostBuilder.ConfigureServices // Or // // Startup.ConfigureServices
The BackgroundProcessing method returns a Task, which is awaited in ExecuteAsync. Background tasks in the queue are dequeued and executed in BackgroundProcessing. Work items are awaited before the service stops in StopAsync.
protectedoverrideasync Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation( $"Queued Hosted Service is running.{Environment.NewLine}" + $"{Environment.NewLine}Tap W to add a work item to the " + $"background queue.{Environment.NewLine}");
await BackgroundProcessing(stoppingToken); }
privateasync Task BackgroundProcessing(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { var workItem = await TaskQueue.DequeueAsync(stoppingToken);
publicvoidStartMonitorLoop() { _logger.LogInformation("Monitor Loop is starting.");
// Run a console user input loop in a background thread Task.Run(() => Monitor()); }
publicvoidMonitor() { while (!_cancellationToken.IsCancellationRequested) { var keyStroke = Console.ReadKey();
if (keyStroke.Key == ConsoleKey.W) { // Enqueue a background work item _taskQueue.QueueBackgroundWorkItem(async token => { // Simulate three 5-second tasks to complete // for each enqueued work item
int delayLoop = 0; var guid = Guid.NewGuid().ToString();
_logger.LogInformation( "Queued Background Task {Guid} is starting.", guid);
while (!token.IsCancellationRequested && delayLoop < 3) { try { await Task.Delay(TimeSpan.FromSeconds(5), token); } catch (OperationCanceledException) { // Prevent throwing if the Delay is cancelled }
if (delayLoop == 3) { _logger.LogInformation( "Queued Background Task {Guid} is complete.", guid); } else { _logger.LogInformation( "Queued Background Task {Guid} was cancelled.", guid); } }); } } } }
The services are registered in IHostBuilder.ConfigureServices (Program.cs). The hosted service is registered with the AddHostedService extension method:
1 2 3 4 5 6 7
// Program.IHostBuilder.ConfigureServices // Or // // Startup.ConfigureServices
// base configuration for DI services.AddQuartz(q => { // handy when part of cluster or you want to otherwise identify multiple schedulers q.SchedulerId = "Scheduler-Core";
// we take this from appsettings.json, just show it's possible // q.SchedulerName = "Quartz ASP.NET Core Sample Scheduler";
// we could leave DI configuration intact and then jobs need to have public no-arg constructor // the MS DI is expected to produce transient job instances q.UseMicrosoftDependencyInjectionJobFactory(options => { // if we don't have the job in DI, allow fallback to configure via default constructor options.AllowDefaultConstructor = true; });
// or // q.UseMicrosoftDependencyInjectionScopedJobFactory();
// these are the defaults q.UseSimpleTypeLoader(); q.UseInMemoryStore(); q.UseDefaultThreadPool(tp => { tp.MaxConcurrency = 10; });
// configure jobs with code var jobKey = new JobKey("awesome job", "awesome group"); q.AddJob<ExampleJob>(j => j .StoreDurably() .WithIdentity(jobKey) .WithDescription("my awesome job") );