ASP.NET Core Background Tasks with IHostedService 

ASP.NET Core supports a easy-to-use method of implementing background task processing. This makes use of the IHostedService interface. These can be run as a standalone project, or as part of a normal ASP.NET Core site. If you want to run it as a standalone project, the Microsoft Documentation is your best guide, and so I won’t be going into further detail on that approach. 

There are more advanced background task management frameworks available such as Hangfire, but for simple use-cases, or when you’re just getting started, a hosted service running within your ASP.NET Core Site will suffice. 

To follow along, start with a blank ASP.NET Core Site template. You can also download the complete source code from GitHub here: https://github.com/MorneZaayman/ASP.NET-Core-Hosted-Service 

To start, I recommend creating a folder to store your hosted services. Then within this folder create a new class file containing a class that inherits from Microsoft.Extensions.Hosting.IHostedService. This will require two methods to be implemented – StartAsync and StopAsync which will execute code when the service starts and stops respectfully. To keep things simple, I will name mine LogCurrentTimeHostedService, and it will just log the current time to the console. A real service could inherit from an interface and do more elaborate work such as send emails, perform file or database maintenance etc.  

public class LogCurrentTimeHostedService : IHostedService 
{ 
    public Task StartAsync(CancellationToken cancellationToken) 
    { 
        throw new NotImplementedException(); 
    } 

    public Task StopAsync(CancellationToken cancellationToken) 
    { 
        throw new NotImplementedException(); 

    } 
} 

Next, we’ll create a constructor that takes an ILogger through dependency injection which we’ll use to log information to the console. 

private readonly ILogger _logger; 

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

Then within the StartAsync method, we’ll write some code to log when the method starts and ends, add a delay to simulate doing some work, and log the current time. 

public async Task StartAsync(CancellationToken cancellationToken) 
{
    _logger.LogInformation($"{GetType().Name} is starting."); 

    await Task.Delay(3000); 

    _logger.LogInformation($"The current time is {DateTime.Now}."); 

    _logger.LogInformation($"{GetType().Name} is finished doing its work in starting."); 
}

We’ll do the same thing in the StopAsync method. 

public async Task StopAsync(CancellationToken cancellationToken) 
{
    _logger.LogInformation($"{GetType().Name} is stopping."); 

    await Task.Delay(3000); 

    _logger.LogInformation($"The current time is {DateTime.Now}."); 

    _logger.LogInformation($"{GetType().Name} is finished doing its work in stopping."); 
}

The final step is to add the hosted service to the Program.cs file. 

builder.Services.AddHostedService<LogCurrentTimeHostedService>(); 

Finally, run the application and watch the console window. You’ll see the information from the StartAsync method being logged to the console window. 

Next, press Ctrl+C to shut down the application and then you’ll see the code from the StopAsync method executing. 

It’s as simple as that.  

There is one caveat to keep in mind when running hosted services within a web project like this. The hosted service gets created for every instance of the application. If you are using something like App Service with multiple instances, you will have one hosted service per instance running. If you have a process that does something like sending an email at a certain time, it will execute that multiple times – one for every instance running.  

Leave a comment

Your email address will not be published.