net-core
  1. net-core-create-and-host-background-services

Create and host background services - ASP.NET Core Background Services

ASP.NET Core provides a powerful mechanism for creating long-running background tasks. These background tasks can perform operations such as processing logs, sending emails, and retrieving data from third-party APIs. In this page, we will discuss how to create and host background services in ASP.NET Core.

Syntax

To create a background service in ASP.NET Core, you need to create a class that implements the IHostedService interface. The IHostedService interface defines two methods: StartAsync and StopAsync. You should add the logic of your background task in the StartAsync method.

Here's the syntax for creating a background service:

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;

public class MyBackgroundService : IHostedService, IDisposable
{
    private Timer _timer;

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        // Add the background task logic here
        Console.WriteLine("Background task is running");
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}

Example

Here's an example of how to host a background service in an ASP.NET Core web application:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHostedService<MyBackgroundService>();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Configure middleware, routing, etc.
    }
}

In the example above, we add the MyBackgroundService to the dependency injection container by calling AddHostedService in the ConfigureServices method of the Startup class. The AddHostedService method registers the background service with the dependency injection container, and the service will be started when the application starts and stopped when the application shuts down.

Output

When you run the ASP.NET Core application, the background service will start running, and you will see the output in the console window.

Background task is running
Background task is running
Background task is running
...

Exaplanation

ASP.NET Core Background services are used to perform long-running tasks which should not block the application. It is like a background thread which runs indefinitely and can be used to do tasks like processing queues, processing email messages, updating database from external sources, or fetching data from external sources.

Use

Background services in ASP.NET Core are useful in scenarios that require long-running processes such as monitoring a file system for changes, sending emails to users in the background, or periodically updating data in a database.

Important Points

  • Background services should implement the IHostedService interface.
  • The StartAsync method should contain the logic for the background task.
  • The StopAsync method should contain the logic to stop the background task.
  • The class should implement IDisposable interface.

Summary

In this page, we discussed how to create and host background services in ASP.NET Core. We covered the syntax, example, output, explanation, use, and important points of ASP.NET Core background services. By using background services in your ASP.NET Core applications, you can run long-running tasks that require minimal supervision and don't block the main thread.

Published on: