Implement Background Tasks In Microservices With IHostedService And BackgroundService Class In .NET

Introduction 

 
In this article, we try to understand how we can implement background tasks in microservices using these IHostedService and BackgroundService classes.
 
Background tasks can be implemented in two ways: Implementing IHostedService Interface and Inheriting BackgroundService Class.
 
Background Task that run on a Timer. To run Background tasks, we dont need any Nuget packages.
 
For a class derived from IHostedService, we need to implement two methods, given below:
  • StartAsync
  • StopAsync 
.NET Core 2.1 has a new feature called IHostedService which allows developers to run a background service that can managed lifetime to its caller, it is part of a Console Application or ASP.NET core application. If we inherit abstract base BackgroundService class, then we need to implement the ExecuteAsync method.
 
BackgroundService is an abstract base class for implementing a long-running IHostedService.Using BackgroundService class we can write less code as compared to IHostedService. This is because in the BackgroundService abstract class, we have only one method(ExecuteAsync) which we need to implemented and in IHostedService we have two methods (StartAsync and StopAsync). In short, we can say like in BackgroundService class we need to handle only one ExecuteAsync method and in IHostedService we need to handle two methods, StartAsync and StopAsync.In BackgroundService we need to implement Task ExecuteAsync(CancellationToken stopCancel) while handling the CancelationToken that is used to determine when to stop your particular method. By using BackgroundService in .NET Core, it provides a convenient way to create a long-running process in a .NET application. By default, the CancelationToken setup with 5 Seconds timeout. It means your services are expected to cancel within 5 seconds. You can change that value by using the UseShutdownTimeout extension of the IWebHostBuilder.If you need service to be running all the time then you could use windows service for this requirement.
 
Let me show you one diagram so it will be easy to understand:
In this above diagram, as we can see BackgroundService inheriting from MyService and implementing IHostedService.The default behavior of this Background Service is like StartAsync method calls ExecuteAsync.The IHostedService interface provides a nice way to properly start background tasks in web applications. 
  • StartAsync is nothing but triggered when the application host is ready to start the service. 
  • It contains the logic to start the background task.
  • StartAsync is called before the app request processing the pipeline is configured (Startup. Configure) and the server is started and the IApplicationLifetime.ApplicationStarted is triggered.
  • StopAsync is triggered when the application host is performing a graceful shutdown.
  • It contains the logic to end the background task.
  • Any method called in StopAsync should return promptly.
  • Implement IDisposable and finalizers to dispose of any unmanaged resources.
  • The IHostedService interface provides a nice way to properly start Background tasks in web applications.
  • BackgroundService is an abstract base class for implementing a long-running IHostedService.
  • It contains less code as compared to IHostedService. Because in BackgroundService we have only one method to handle which is Task ExecuteAsync (CancellationToken cancellationtoken).But in IHostedService we need to handle to methods which is Task StartAsync (CancellationToken cancellationtoken) and Task StopAsync (CancellationToken cancellationtoken).
  • ExecuteAsync () is called to run background service.
  • The implementation returns a Task that represents the entire lifetime of the background service. No further services are started until ExecuteAsync becomes Asynchronous, such as by calling await.
  • Avoid performing long, blocking initialization work in ExecuteAsync ().The host blocks in StopAsync waiting for ExecuteAsync () to complete.
  • The cancellation token is triggered when IHostedService.StopAsync is called. Your implementation ExecuteAsync should be finished promptly when the cancellation token fired in order to gracefully shut down the service. Otherwise, the service ungracefully shuts down at the shutdown timeout.
  • By Default CancellationToken setup with 5 Seconds timeout. It means your service is expected to cancel within 5 seconds.
  • We can change the value by using the UseShutdownTimeout Extension of the IWebHostBuilder.
  • The default behavior of BackgroundService is like StartAsync method calls ExecuteAsync method.
I hope you understand the concept of how we can implement Background Task in Microservices with the help of these two IHostServices and BackgroundService class. In the next article, we will try to understand through an example.