How to use IHostedService in ASP. Net Core

  • 2021-11-24 01:17:20
  • OfStack

In our applications, there are often some requirements for performing background tasks and task scheduling. How can we implement them in ASP. Net Core? You can use Azure, WebJobs or some other third-party task scheduling framework, such as Quartz and Hangfire.

In ASP. Net Core, the background task can also be used as the mode of hosting service. The so-called hosting service only needs to implement the IHostedService interface in the framework and include the business logic you need as the background task. This article will discuss how to build hosting service in ASP. Net Core.

Create a managed service

To create a managed service, you only need to implement the IHostedService interface, and the following is the declaration of the IHostedService interface.


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

In this section, we do a minimalist managed service in ASP. Net Core. First, customize an MyFirstHostedService managed class with the following code:


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

Create BackgroundService

One thing to note is that MyFirstHostedService in the previous section implements the IHostedService interface, which is not required in actual development, because the abstract class BackgroundService is already provided in. Net Core, so you can rewrite the ExecuteAsync method of the abstract class next, as shown in the following code:


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

The following code snippet shows a simple Log method for recording the current time to a file, which is triggered by the managed service.


    private async Task Log()
    {
      using (StreamWriter sw = new StreamWriter(@"D:\log.txt",true))
      {
        await sw.WriteLineAsync(DateTime.Now.ToLongTimeString());
      }
    }

Use the ExecuteAsync method

Next, look at how to implement the ExecuteAsync method, whose logic is to call the Log () method periodically (second/s), as shown in the following code:


  protected async override Task ExecuteAsync(CancellationToken token)
  {
    while (!token.IsCancellationRequested)
    {
      await Log();
      await Task.Delay(1000, token);
    }
  }

Ok, the following is the complete MyFirstHostedService class code for reference only.


using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace HostedServicesApp
{
  public class MyFirstHostedService : BackgroundService
  {
    protected async override Task ExecuteAsync(CancellationToken token)
    {
      while (!token.IsCancellationRequested)
      {
        await Log();
        await Task.Delay(1000, token);
      }
    }
    private async Task Log()
    {
      using (StreamWriter sw = new StreamWriter(@"D:\log.txt",true))
      {
        await sw.WriteLineAsync(DateTime.Now.ToLongTimeString());
      }
    }
  } 
}

Hosted service registration

The managed service class is written, and to inject it into Asp. NET Core, you need to inject the managed service class into ServiceCollection in Startup. ConfigureServices, as shown in the following code:


  public void ConfigureServices(IServiceCollection services)
  {
    services.AddHostedService<MyFirstHostedService>();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  } 

When you run the application, you will see that the program logs to the D:\ log. txt file every second.

StartAsync and StopAsync provided in IHostedService can be used to perform or stop background tasks in ASP. NET Core, you can use it to update data or other operations in your application, and these periodic business logic runs in the background thread, so that it will not cause the main request thread to block.

Translation link: https://www.infoworld.com/article/3390741/how-to-use-ihostedservice-in-aspnet-core. html


Related articles: