Background Task Creation with Hosted Services and Workers

Introduction

In a web application, there are tasks that need to be performed in the background, such as sending emails, processing data, or performing regular maintenance. These tasks are often non-HTTP-related and can be time-consuming, so it's best to offload them from the main request-response cycle. In ASP.NET Core, you can use hosted services and background workers to accomplish this.

Here's a step-by-step example of how to create background tasks using hosted services and background workers in an ASP.NET Core application.

Create a new ASP.NET Core Web Application

Create a new ASP.NET Core project using your preferred development environment (Visual Studio, Visual Studio Code, etc.). You can choose the "Web Application" template.

Add a BackgroundService

In ASP.NET Core, you can use the BackgroundService base class to create a hosted service that runs in the background. Let's say you want to simulate sending emails as a background task.

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

Author: Sardar Mudassar Ali Khan
namespace BackgroundTasksExample.BackgroundServices
{
    public class EmailSender : BackgroundService
    {
        private readonly ILogger<EmailSender> _logger;

        public EmailSender(ILogger<EmailSender> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Sending emails...");
                // Simulate email sending logic here
                await Task.Delay(TimeSpan.FromMinutes(30), stoppingToken); // Delay between tasks
            }
        }
    }
}

Register the BackgroundService:

In your Startup.cs class, add the following code to register your EmailSender as a hosted service.

using BackgroundTasksExample.BackgroundServices;

Author: Sardar Mudassar Ali Khan

public void ConfigureServices(IServiceCollection services)
{
    services.AddHostedService<EmailSender>();
}

Run the Application

Run your ASP.NET Core application, and the EmailSender background service will start executing in the background. It will repeatedly log that it's sending emails, and you can replace the placeholder logic with your actual email-sending code.

Conclusion

Using hosted services and background workers in an ASP.NET Core application provides an effective way to handle non-HTTP-related tasks asynchronously and in the background. This approach helps improve the responsiveness of your web application by offloading time-consuming tasks from the main request-response cycle. Let's recap the key points:

  1. BackgroundService: The BackgroundService base class enables you to create a hosted service that runs in the background. You can inherit from this class and override the ExecuteAsync method to define the background task's logic.
  2. Registration: Register your background service in the Startup.cs class using the AddHostedService method. This ensures that your background task is managed by the ASP.NET Core application's built-in background worker infrastructure.
  3. Async Execution: The background service's ExecuteAsync method contains the actual logic of the background task. Make sure to use asynchronous programming patterns when performing long-running operations.
  4. Cancellation Token: ASP.NET Core provides a cancellation token that allows your background service to gracefully stop when the application is shutting down.
  5. Exception Handling: Implement proper exception handling within your background service to handle errors and failures gracefully. This prevents the service from crashing and helps in troubleshooting.
  6. Configuration: Consider adjusting configuration options for your background service, such as intervals between tasks or other relevant settings, based on your application's requirements.

Remember that this approach is versatile and can be used for various types of background tasks, such as sending emails, processing data, and performing regular maintenance. By implementing background services and workers effectively, you can enhance the overall performance, scalability, and responsiveness of your ASP.NET Core web application.