Tuesday, April 18, 2023

What is a background task in .NET Core and how do you implement one?

In .NET Core, a background task is a long-running operation that executes asynchronously in the background while the main application continues to execute other tasks. Background tasks are typically used for operations that do not need to be executed in the foreground or in response to user input, but instead, can run continuously or periodically.

To implement a background task in .NET Core, you can use the BackgroundService class. This is an abstract base class that provides a framework for creating long-running background tasks. To create a background task, you need to derive a class from BackgroundService and implement the ExecuteAsync method.

Here is an example of a simple background task that logs a message to the console every 5 seconds:

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

public class MyBackgroundService : BackgroundService
{
    private readonly ILogger<MyBackgroundService> _logger;

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

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Background task is running...");

            await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
        }
    }
}


In this example, the ExecuteAsync method contains a while loop that runs indefinitely until the cancellation token is requested. Within the loop, a log message is written to the console and then a delay of 5 seconds is used to pause the background task before running again.

To start the background task, you can register it with the .NET Core dependency injection system and add it to the list of hosted services:

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

public static class Program
{
    public static async Task Main(string[] args)
    {
        var hostBuilder = Host.CreateDefaultBuilder(args)
            .ConfigureServices(services =>
            {
                services.AddHostedService<MyBackgroundService>();
            });

        await hostBuilder.RunConsoleAsync();
    }
}


Once the application is started, the background task will run continuously until the application is stopped or the cancellation token is requested.

No comments:

Post a Comment

Please keep your comments relevant.
Comments with external links and adult words will be filtered.