How to Run Background Tasks in ASP.NET Core with Hosted Services

By FoxLearn 12/19/2024 9:52:02 AM   35
One of the features I appreciate most about .NET Core is how easily it allows you to implement and run background tasks in an ASP.NET Core project.

Background tasks are particularly useful in microservices architectures, where you often need to implement a messaging service like RabbitMQ to listen for and consume messages from a message queue.

Start by creating a new ASP.NET Core web application, then create a new class named HelloWorldHostedService.

This class will implement the IHostedService interface.

public class HelloWorldHostedService : IHostedService
{
    private Timer _timer;

    // Run the logic when the service starts
    public Task StartAsync(CancellationToken cancellationToken)
    {
        // Register the background task using a timer
        RegisterTimerTask();
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        Debug.WriteLine("Stopping task...");
        return Task.CompletedTask;
    }

    private void RegisterTimerTask()
    {
        // Call HelloWorld every 5 seconds in the background
        _timer = new Timer(HelloWorld, null, 0, 5000);
    }

    void HelloWorld(object state)
    {
        Debug.WriteLine($"{DateTime.Now}");
        Debug.WriteLine("Hello World!");
        Debug.WriteLine("This is a hosted service");
    }
}

The IHostedService interface requires you to implement StartAsync() and StopAsync() methods. In our example, we use a timer to invoke the HelloWorld() method every 5 seconds.

  • In the StartAsync() method, we register the timer by calling the RegisterTimerTask() method.
  • In the StopAsync() method, we simply log a message when the service stops.

Now, open your Startup.cs file and register the hosted service:

// Register the hosted service
services.AddHostedService<HelloWorldHostedService>();

Run your application.

You should see the background task running in the Output window of Visual Studio, printing the "Hello World" message every 5 seconds.

Alternatively, you can use the BackgroundService class, which is a simplified base class for running background tasks in ASP.NET Core.

public class HelloWorldBackgroundService : BackgroundService
{
    protected async override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            Debug.WriteLine("Background service running!! Hello!");
            await Task.Delay(8000, stoppingToken);
        }
    }
}

Similar to the previous approach, you need to register the background service in your Startup.cs file:

// Register the background service
services.AddHostedService<HelloWorldBackgroundService>();

That's all there is to creating a simple background task in an ASP.NET Core application. Whether you use IHostedService or BackgroundService, the process is straightforward:

  1. Create a class that implements IHostedService or BackgroundService.
  2. Implement the logic for the background task.
  3. Register the service in your Startup.cs file.