AspNetCore.Docs/aspnetcore/fundamentals/hosted-services.md

5.1 KiB

title author description manager ms.author ms.custom ms.date ms.prod ms.technology ms.topic uid
Background tasks with hosted services in ASP.NET Core guardrex Learn how to implement background tasks with hosted services in ASP.NET Core. wpickett riande mvc 02/15/2018 asp.net-core aspnet article fundamentals/hosted-services

Background tasks with hosted services in ASP.NET Core

By Luke Latham

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.
  • Queued background tasks that run sequentially.

View or download sample code (how to download)

IHostedService interface

Hosted services implement the IHostedService interface. The interface defines two methods for objects that are managed by the host:

The hosted service is a singleton that's activated once at app startup and gracefully shutdown at app shutdown. When IDisposable is implemented, resources can be disposed when the service container is disposed. If an error is thrown during background task execution, Dispose should be called even if StopAsync isn't called.

Timed background 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:

[!code-csharp]

The service is registered in Startup.ConfigureServices:

[!code-csharp]

Consuming a scoped service in a background task

To use scoped services within an IHostedService, 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, ILogger is injected into the service:

[!code-csharp]

The hosted service creates a scope to resolve the scoped background task service to call its DoWork method:

[!code-csharp]

The services are registered in Startup.ConfigureServices:

[!code-csharp]

Queued background tasks

A background task queue is based on the .NET 4.x QueueBackgroundWorkItem (tentatively scheduled to be built-in for ASP.NET Core 2.2):

[!code-csharp]

In QueueHostedService, background tasks (workItem) in the queue are dequeued and executed:

[!code-csharp]

The services are registered in Startup.ConfigureServices:

[!code-csharp]

In the Index page model class, the IBackgroundTaskQueue is injected into the constructor and assigned to Queue:

[!code-csharp]

When the Add Task button is selected on the Index page, the OnPostAddTask method is executed. QueueBackgroundWorkItem is called to enqueue the work item:

[!code-csharp]

Additional resources