If you are building a web application, you may have encountered scenarios where some operation needs to be performed indefinitely. So how to handle such scenarios? An efficient way to tackle such scenarios is by using background services. In this tutorial, we will be learning how to create background services in the .NET Core web applications. The .NET Core is Microsoft's offering for building cross-platform applications and now its gaining popularity more than ever.
But first, let's understand more about background services below:
A Short Introduction to Background Services
First, let us discuss why do we need background tasks. In any application, there is a main thread that is responsible for the execution of the application. This thread accepts the requests, performs logic, and finally returns the output.
But there are scenarios where you don't want to delegate your jobs to this main thread. For instance:
- You have to process images or manipulation of media. Image processing and image manipulation, for instance, is a resource extensive task; hence it is more suited for background operation.
- You might want to schedule some jobs for some specific time of day or at any particular time of day. For example, you might need to send the emails to your subscribers at midnight. Background jobs offer a perfect solution for this.
- You have to continuously listen for some event. This event can be either internal or external. For example, you might have an application that reacts to the change in the forex rates. So this process runs throughout the lifetime of the application. Hence we can initiate this process in the background and let it listen.
- You have to perform IO operations that are extensive such as reading the disk for files. Reading lengthy files, which can be from gigabytes to terabytes, if we perform this operation on the main thread, it will freeze the application resulting in a downgraded user experience. Hence having background service taking care of this extensive task provides a smoother user experience.
- You want to periodically perform house keeping operations such as database cleaning, update secondary database or garbage collections operations.
Options Available
Now that you are equipped about the background tasks, let's look at the options available to you to build them. The .NET Core offers three classes to assist you with it: IHostedService and BackgroundService.
Other options are not offered by .NET Core, rather third party offerings. You can use the Hangfire library or opt for some cloud based solution.
Here in this tutorial, we will stick to the solutions provided by the .NET Core.
We will be creating a service that continuously prints out time after every second until the application shuts down.
IHostedService
The IHostedService
is an interface that provides the base for implementing the background services or tasks. For any class to operate as a background service, it must implement this interface. Once implemented, the implementing class has to override two methods: StartAsync(CancellationToken)
and StopAsync(CancellationToken)
.
Next, this hosted service must be registered in the application during the startup of the application. You can register the hosted service in the application by calling the method: AddHostedService<Your_Class>()
.
Let's create our service using IHostedService
For the sake of simplicity, I am using the ASP.NET Core WebAPI project. You can create a new project in Visual Studio to get started.
Now within this project, create a new file called ImplementIHostedService.cs
. This class is basically our service and it implements the IHostedService
interface. Add the below code in this file:
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace WebApplication3.Services
{
public class ImplementIHostedService : IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
Task.Run(async () =>
{
while (!cancellationToken.IsCancellationRequested)
{
Console.WriteLine($"Respponse from IHostedService - {DateTime.Now}");
await Task.Delay(1000);
}
});
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Shutting down IHostedService");
return Task.CompletedTask;
}
}
}
Next, you will need to register this service in the service registration. Open the Startup.cs
file and add the below line in the ConfigureServices
method:
services.AddHostedService<ImplementIHostedService>();
Now run the project and you will see the console returning back the output after one-second delay. If you close the application you will see the output Shutting down IHostedService
message.
To summarize:
- First we create the class that represents our background service.
- Next, we implement the
IHostedService
in this class. - You will need to override two critical methods in your class:
StartAsync
andStopAsync
. - In the
StartAsync
, we fire a new task that performs the background job for us. This task runs in the background and perform the long running operation. - Finally, we override the
StopAsync
method. We do this to handle any clean up tasks when the application is shut down.
Let's create our service using BackgroundService
Here, we will create the same functionality by inheriting BackgroundService
. The BackgroundService
is an abstract
class provided by .NET Core that implements IHostedService
but conceals the mechanics behind it. As we shall see the implementation becomes very clean in BackgrounfService
.
In your ASP.NET Core WebApi project, create a new file called ImplementBackgroundService.cs
. Add the below code in this file:
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace WebApplication3.Services
{
public class ImplementBackgroundService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine($"Respponse from Background Service - {DateTime.Now}");
await Task.Delay(1000);
}
}
}
}
Here we do not have to worry about the StartAsync
or StopAsync
methods. Rather, we have a single method called ExecuteAsync
. We override this method to add our functionality. The point to note here is we do not have to create a new Task
when working with BackgroundService
. Rather the service works in the background.
Finally, we have to register our service in the Startup.cs
file. Add the below line of code in the method ConfigureServices
of the Startup.cs
file:
services.AddHostedService<ImplementBackgroundService>();
Run the application and you will see the similar output here as well.
When to Use IHostedService
and BackgroundService
IHostedService
The IHostedService
provides the basic framework for building the background operations. It gives developers the control to begin and end the operations. Having this control allows development of complex scenarios where manual tweaks are needed. Developers opt for this way when they need to build scenarios that are complex and require careful implementation for starting and stopping of the service.
BackgroundService
The BackgroundService
abstracts the working of the code and provides a simple way to initiate long-running tasks. For scenarios that are simple and do not require much tweaking, BackgroundService
offers a readily available solution to jump-start the development. Therefore developers prefer it when they just want to get started with the task without having to worry much about the mechanics.
Conclusion
In this tutorial, we looked at how we can setup background tasks. These tasks are very helpful in running and processing the information concealed from the user. If properly used, these services can drastically improve the overall experience of the web application and make the processing faster. You can handle long running tasks that require huge computing resources and memory in efficient manner.
--
Feel free to browse through the other sections of the blog where you can find many other amazing articles on Programming and IT!
And if you are interested in joining our amazing team and working with top U.S. based clients, then apply here and take your career to the next level.
Top comments (0)