How to use IHostedService in ASP.NET Core

By FoxLearn 1/7/2025 6:45:37 AM   25
In ASP.Net Core, you can implement background tasks by using Azure WebJobs or various third-party task schedulers such as Quartz or Hangfire.

A hosted service is a class that implements the `IHostedService` interface and contains the necessary logic to run tasks in the background.

Creating a hosted service in ASP.NET Core

To create a hosted service, we need to implement the IHostedService interface.

public interface IHostedService
{
    Task StartAsync(CancellationToken cancellationToken);
    Task StopAsync(CancellationToken cancellationToken);
}

In this section, we will walk through creating a basic hosted service implementation in ASP.Net Core.

Follow these steps to create a new hosted service:

  1. In the Solution Explorer window, select your project.
  2. Right-click and choose "Add -> Class..."
  3. In the "Add New Item" window, give the class a name (e.g., MyHostedService).
  4. Click "Add."

This will create a new class named MyHostedService in a file of the same name with a .cs extension. Now replace the default MyHostedService class with the following code:

public class MyHostedService : IHostedService
{
    protected async override Task ExecuteAsync(CancellationToken token)
    {
        throw new NotImplementedException();
    }
}

Using the BackgroundService class in ASP.NET Core

In .NET Core, the abstract BackgroundService class implements the IHostedService interface, and we can modify our code to inherit from this class.

public class MyHostedService : BackgroundService
{
    protected async override Task ExecuteAsync(CancellationToken token)
    {
        throw new NotImplementedException();
    }
}

The following code snippet demonstrates a simple method to log a custom message to a text file. This method will be invoked by our hosted service.

private async Task LogMessage()
{
    using (StreamWriter sw = new StreamWriter(@"C:\logs\appLog.txt", true))
    {
        await sw.WriteLineAsync("Service started at: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
    }
}

Using the ExecuteAsync method in ASP.NET Core

For example, how the ExecuteAsync method is implemented.

protected async override Task ExecuteAsync(CancellationToken token)
{
    while (!token.IsCancellationRequested)
    {
        await LogMessage();
        await Task.Delay(2000, token);  // Delay set to 2 seconds
    }
}

Notice that the LogMessage method we created earlier is called from within this method at regular intervals (every two seconds).

And here is the complete source code for the CustomBackgroundService for your reference:

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

namespace HostedServicesApp
{
    public class MyHostedService : BackgroundService
    {
        protected async override Task ExecuteAsync(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                await LogMessage();
                await Task.Delay(2000, token);  // Delay set to 2 seconds
            }
        }

        private async Task LogMessage()
        {
            using (StreamWriter sw = new StreamWriter(@"C:\logs\appLog.txt", true))
            {
                await sw.WriteLineAsync("Service running at: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }
        }
    }
}

Register the hosted service in ASP.NET Core

Finally, you need to register the hosted service in the Startup class.

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

When you run this ASP.NET Core application, a log file will be created at the specified location, and the current time will be logged every two seconds.

The IHostedService interface is useful for starting and stopping background tasks in an ASP.NET Core web application. You can use this interface to implement a custom hosted service that can gracefully cancel and shut down if needed. A common use case for a hosted service is running background tasks, such as updating content or data in your application, without blocking the main request thread.