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:
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:
1. 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.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.
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>()
.
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:
Now run the project and you will see the console returning back the output after a one-second delay. If you close the application you will see the output Shutting down IHostedService
message.
To summarize:
IHostedService
in this class.StartAsync
and StopAsync
.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.StopAsync
method. We do this to handle any clean up tasks when the application is shut down.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.
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.
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.
--
If you want to stay up to date with all the new content we publish on our blog, share your email and hit the subscribe button.
Also, feel free to browse through the other sections of the blog where you can find many other amazing articles on: Programming, IT, Outsourcing, and even Management.
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.
With over +16 years of experience in the technology and software industry and +12 of those years at Jobsity, Santi has performed a variety of roles including UX/UI web designer, senior front-end developer, technical project manager, and account manager. Wearing all of these hats has provided him with a wide range of expertise and the ability to manage teams, create solutions, and understand industry needs. At present, he runs the Operations Department at Jobsity, creating a high-level strategy for the company's success and leading a team of more than 400 professionals in their work on major projects.