code-snippets/docs/dotnet/background-service.md

57 lines
2.3 KiB
Markdown
Raw Normal View History

2024-10-11 09:38:58 +11:00
# Background Services
Often in application you will want logic to execute in the background. This could be for a variety of reasons, such as:
* Processing data
* Sending emails
* Performing maintenance tasks
* Running scheduled jobs
In .NET Core, you can create a background service by creating a class that inherits from the `BackgroundService` class. This class is part of the `Microsoft.Extensions.Hosting` namespace.
::: warn
The ability of a background service to run is dependent on the lifetime of the host. If the host is stopped, the background service will also stop. This means for software running in IIS you will need to ensure the site is always running. For this reason docker deployments are usually preferred
:::
## Creating a Background Service
To create a background service, you need to create a class that inherits from the `BackgroundService` class. This class has a single method that you need to override, called `ExecuteAsync`. This method is called when the background service is started, and it should contain the logic that you want to run in the background.
Here is an example of a simple background service that writes to the console every second:
```csharp
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
namespace BackgroundServiceExample
{
public class MyBackgroundService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine("Background service is running...");
await Task.Delay(1000);
}
}
}
}
```
## Registering the Background Service
The next step is to register the background service with the dependency injection container. You can do this in `Program.cs` when you are building the host.
```csharp
// ...
builder.Services.AddHostedService<MyBackgroundService>();
// ...
```
## Conclusion
This is just a simple way to use background services, for more complex scenarios you may want to look at writing a console app that runs as a service which can be triggered by a scheduler or a message queue. This will also give you flexibility to run the service on a different machine or in a container and have separate configuration and so on.