Updated March 28, 2023
Introduction to ASP.NET Core Hosted Service
ASP.NET Core Hosted Service is the class where background logical task that implements the IHostedService Interface, the background tasks implemented as hosted services, and those executes on a timer. This hosted service is activated as scoped service, and it uses the Dependency Injection (DI). IHostedService interface offers the best method to properly initiate the background tasks in web applications.
What is ASP.NET Core Hosted Service?
The ASP.NET Core Hosted Service defines the background tasks in the day-to-day in developers team. It is the class where the background logical task which implements the IHostedService Interface, the background tasks are implemented as the hosted services. For the execution of the background task, we do not require any packages like NuGet; it will be available in ASP.NET Core infrastructure itself. To know the background task implemented in two ways in ASP.NET Core, they use IHostedService as Interface and use BackgroundService Class and IHostedService.
It consists of two methods: StartAsync (CancellationToken) and StopAsync(CancellatioToken). The StartAsync is a trigger it starts the service once the application host is ready to start; it consists of the start background tasks logics. The StartAsync is called before the process request pipeline configures(Startup.Configured), and it starts the server and triggers IApplicationLifeTime.ApplicationStarted. The application host is performing the shutdown process; it triggers the StopAsync. IHostedService interface offers a better method to startBackground tasks in Web Applications.
How to use hosted service?
- To host the service, we need to follow such things they are,
- To build the Windows Service by using the BackgroundService
- Create the Queue Service.
- Host the Core in Windows Service. Background task hosted with the services on ASP.NET Core.
- To implement the tasks in the background in MicroServices with IHostedService and BackgroundService classes. Also, to implement the interface IHostedService.
Create ASP.NET Core Hosted Service
To create the new ASP.NET Core Hosted Service, just click on File and select New, then choose the suitable project template in Visual Studio (VS)
Then just by click on “Next” to create and give the suitable name for the project,
It then creates the project and the project structure; look at this as shown below,
Once completing the above process then we have to create the class library for the project, right-click on the solution explorer, and include the new class library for the Hosted Service, then the project structure looks like as shown below,
After that to install the Hosted Service from the NuGet Package by running the below command as shown,
Install-Package Microsoft.Extensions.Hosting-Version 3.1.2
We need to give in the Class Library Project of NuGet Package Manager Console. Once executing/ running the command on Console, it like as shown below
To add an interface as “IBackgroundTaskQueue,” right-click on the class library project. To add the new class, just right-click and include the class called “BackgroundTaskQueue” to inherit the interface “IBackgroundTaskQueue.” To build two methods as enqueue and dequeue as the requests as shown below,
The thread-safe class is the concurrent queue used to read and write the various requests into the queue, which offers the data structure FIFO. When getting various requests simultaneously, it puts the queue and processes them step by step.
Implementing ASP.NET Core Hosted Service
To set the number of threads, we need to use the SemaphoreSlim to run concurrently. Let’s see an example if we setting to 2 and if we having 5 requests in a queue, it will pick up 2 in parallel.
public class BackgroundTaskQueue : IBackgroundTaskQueue
{
private ConcurrentQueue<Func<CancellationToken, Task>> _workItems =
new ConcurrentQueue<Func<CancellationToken, Task>>();
private SemaphoreSlim _signal = new SemaphoreSlim(0);
public void QueueBackgroundWorkItem(
Func<CancellationToken, Task> workItem)
{
if (workItem == null)
{
throw new ArgumentNullException(nameof(workItem));
}
_workItems.Enqueue(workItem);
_signal.Release();
}
public async Task<Func<CancellationToken, Task>> DequeueAsync(
CancellationToken cancellationToken)
{
await _signal.WaitAsync(cancellationToken);
_workItems.TryDequeue(out var workItem);
return workItem;
}
}
For including the method declaration in the interface, the interface looks like as given below,
public interface IBackgroundTaskQueue
{
void QueueBackgroundWorkItem(Func<CancellationToken, Task> workItem);
Task<Func<CancellationToken, Task>> DequeueAsync(
CancellationToken cancellationToken);
}
To add a new class with the name of “QueuedHostedService,” just by right-clicking and include, then inherit the “BackgroundService” from Microsoft.Extensions.Hosting
public class QueuedHostedService : BackgroundService
{
private readonly ILogger _logger;
public QueuedHostedService(IBackgroundTaskQueue taskQueue,
ILoggerFactory loggerFactory)
{
TaskQueue = taskQueue;
_logger = loggerFactory.CreateLogger<QueuedHostedService>();
}
public IBackgroundTaskQueue TaskQueue { get; }
protected async override Task ExecuteAsync(
CancellationToken cancellationToken)
{
_logger.LogInformation("Queued Hosted Service is starting.");
while (!cancellationToken.IsCancellationRequested)
{
var workItem = await TaskQueue.DequeueAsync(cancellationToken);
try
{
await workItem(cancellationToken);
}
catch (Exception ex)
{
_logger.LogError(ex,
"Error occurred executing {WorkItem}.", nameof(workItem));
}
}
_logger.LogInformation("Queued Hosted Service is stopping.");
}
}
Once completing the class library then to invoke it to make use of it,
BackgroundService is a base class
To invoke the backgroundservice in Core Web API, which is a base case, to call up the background service in core Web API right click on the dependencies in the web project to add the class library reference to the solution as shown below,
In the Startup.cs file, inject the following dependencies,
- AddHostService<QueuedHostService>();
- AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();
Once done, then go to the controller class to inject “IBackgroundTaskQueue” then to invoke the method called “QueueBackgroundWorkItem” as shown below,
Use the interface IServiceScopeFactory from Microsoft.Extension.Dependency Injection the main thing is that when API returns its response, the entire service, including the DB Context, gets disposed of, again to build up the IServiceScopeFactory.
public class WeatherForecastController : ControllerBase
{
public IBackgroundTaskQueue _queue { get; }
private readonly IServiceScopeFactory _serviceScopeFactory;
public WeatherForecastController(IBackgroundTaskQueue queue, IServiceScopeFactory serviceScopeFactory)
{
_queue = queue;
_serviceScopeFactory = serviceScopeFactory;
}
[HttpGet]
public IActionResult Get()
{
_queue.QueueBackgroundWorkItem(async token =>
{
using (var scope = _serviceScopeFactory.CreateScope())
{
var scopedServices = scope.ServiceProvider;
int j = 1000;
for (int i = 0; i < j; i++)
{
Console.WriteLine(i);
}
await Task.Delay(TimeSpan.FromSeconds(5), token);
}
});
return Ok("In progress..");
}
}
Once completing this API, we will getting the response as “In progress..” then the background tasks call up and keep on executing into the loop which is created in code,
The API is returned with a message & the background service starts running.
Recommended Articles
We hope that this EDUCBA information on “ASP.NET Core Hosted Service” was beneficial to you. You can view EDUCBA’s recommended articles for more information.