In our applications, there are often some requirements for performing background tasks and task scheduling, so how to implement it in Core? You can use Azure WebJobs or some other third-party task scheduling frameworks, such as Quartz and Hangfire.
In Core, you can also use background tasks as a hosting service model. The so-called hosting service only needs to implement the IHostedService interface in the framework and include the business logic you need as a backend task. This article will discuss how to build hosting services in Core.
Create a hosting service
To create a hosting service, you only need to implement the IHostedService interface. The following is the declaration of the IHostedService interface.
public interface IHostedService { Task StartAsync(CancellationToken cancellationToken); Task StopAsync(CancellationToken cancellationToken); }
In this section, we create a minimalist version of hosting service in Core. First, we customize a MyFirstHostedService hosting class, with the code as follows:
public class MyFirstHostedService : IHostedService { protected async override Task ExecuteAsync(CancellationToken token) { throw new NotImplementedException(); } }
Create BackgroundService
One thing to note is that the MyFirstHostedService in the previous section implements the IHostedService interface. This does not need to be done 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, 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 logging the current time into a file, triggered by the managed service.
private async Task Log() { using (StreamWriter sw = new StreamWriter(@"D:\",true)) { await (()); } }
Use the ExecuteAsync method
Next, let’s take a look at how to implement the ExecuteAsync method. The logic of this method is to call the Log() method periodically (second/s), as shown in the following code:
protected async override Task ExecuteAsync(CancellationToken token) { while (!) { await Log(); await (1000, token); } }
OK, here is the complete MyFirstHostedService class code for reference only.
using ; using System; using ; using ; using ; namespace HostedServicesApp { public class MyFirstHostedService : BackgroundService { protected async override Task ExecuteAsync(CancellationToken token) { while (!) { await Log(); await (1000, token); } } private async Task Log() { using (StreamWriter sw = new StreamWriter(@"D:\",true)) { await (()); } } } }
Hosting Service Registration
The managed service class has been written. To inject it into Core, you need to inject the managed service class into ServiceCollection in , as shown in the following code:
public void ConfigureServices(IServiceCollection services) { <MyFirstHostedService>(); ().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
When the application is run, you will see that the program will record logs in the D:\ file every second.
StartAsync and StopAsync provided in IHostedService can be used to perform or stop background tasks in Core, which you can use to update data or other operations in your application, and these periodic business logic runs in background threads so that the main request thread does not block.
Translation link:/article/3390741/
This is the end of this article about how to use IHostedService in Core. For more related content on Core, please search for my previous articles or continue browsing the related articles below. IHostedService is the one that IHostedService is used by Core. I hope everyone will support me in the future!