In this article, we will discuss BackgroundSerive in .Net Core. In.NET Core, background services are a mechanism to build long-running processes that run independently of an application's main thread in the background. Typically, these services are used for processing in the background, data synchronization, or sending notifications. In .NET Core, a BackgroundService class offers a mechanism to implement time-consuming background operations in a different thread. It is a component of Microsoft.Extensions.Hosting namespace and is utilized by .NET Core apps to carry out background operations. A background service can be used to carry out operations like email sending, data processing, and scheduled tasks.
Background service is a continuous process that runs asynchronously. It is a component that can carry out operations like data processing, file processing, or monitoring and is created to function without user input. BackgroundServices are helpful for non-time-sensitive operations that can be completed without interfering with the application's regular operation.
Creating a new .NET Core Console Application:
To implement a BackgroundService in .NET Core, we first need to create a new .NET Core Console Application. To do this, follow the steps below:
Open Visual Studio.
Click on "Create a new project".
Select "Console App (.NET Core)" under the "ASP.NET Core" tab.
Name your project and click "Create".
Step - 1 :
Install the Microsoft.Extensions.Hosting NuGet package:
The Microsoft.Extensions.Hosting NuGet package provides a host for .NET Core applications, including a built-in service container, configuration, and logging.
You can install it using the NuGet Package Manager or the Package Manager Console:
NuGet Package Manager: Right-click on your project and select Manage NuGet Packages. Search for Microsoft.Extensions.Hosting and click on Install.
Package Manager Console: Open the console and run the following command:
Install-Package Microsoft.Extensions.Hosting
As you can see in the given below screenshot this is how exact Nuget package you need to install.
Step β 2:
Implementing a BackgroundService:
Once you have created a new .NET Core Console Application, you can implement a BackgroundService. Follow the steps below:
Create a new class called "MyBackgroundService" that inherits from BackgroundService. The MyBackgroundService class will implement the long-running task that we want to run in the background. Add the following code to the MyBackgroundService class:
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
public class MyBackgroundService : BackgroundService
{
readonly ILogger<MyBackgroundService> _logger;
private Timer _timer;
public MyBackgroundService(ILogger<MyBackgroundService> logger)
{
_logger = logger;
}
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine("Running background task...");
_logger.LogInformation("MyBackgroundService is starting {time}", DateTimeOffset.Now);
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
}
}
}
The ExecuteAsync method is called when the BackgroundService starts running. In the ExecuteAsync method, we have an infinite loop that runs until the cancellation token is requested. Inside the loop, we can perform any long-running task that we want the background service to perform. In this example, we are simply delaying for 1 second using the Task.Delay method.
Step β 3:
Add the background service to the service collection:
The next step is to add the background service to the service collection. This will allow the service to be instantiated and started when the application starts.
To add the BackgroundService to the service collection, open the Program.cs file and add the following code:
builder.Services.AddHostedService<MyBackgroundService>();
Step β 4:
Run your BackgroundService:
That's it! Now you can run your BackgroundService by pressing F5 in Visual Studio. You should see "Running background service" printed on the console every 1 second.
Once your application successfully executes then it will automatically open the browser into a Swagger as we have implemented Swagger in our project. As you can see in the given below screenshot:
Meanwhile, it will also run on the command prompt wiondow to see the output and it will run also on the console output screen for the BackgroundService running execution.
As you can the command prompt window output in visual studio to given below images.
Visual studio output:
Console output Screen:
As we can see in the above-mentioned images itβs continuously running the background service every 1 second. You can change the timing of the running process according to your wish. And to stop the running process we just need to type CTRL + C, then it will stop the BackgroundService running process.
Benefits of using BackgroundService in Asp.Net Core:
A BackgroundService is a base class in ASP.NET Core that offers a practical approach to construct a lengthy background activity that runs concurrently with an ASP.NET Core application. This class automatically starts when the application starts and terminates when the application closes because it is made to run as a hosted service for the duration of the application.
Using a BackgroundService is beneficial in several ways:
Provides a standardized approach: A BackgroundService provides a standardized approach to creating a long-running, background task in ASP.NET Core, which can help to ensure consistency and maintainability of the code.
Easy to use and integrate: The BackgroundService class is easy to use and integrate with other components of the ASP.NET Core framework, such as dependency injection.
Runs asynchronously: The BackgroundService runs asynchronously, which means that it doesn't block the main thread of the application and doesn't impact the performance of the application.
Auto-starts and stops: The BackgroundService is automatically started when the application starts and stopped when the application shuts down, so you don't need to worry about managing the lifecycle of the background task.
Ideal for background processing: The BackgroundService is ideal for performing background processing tasks, such as sending emails, processing data, and performing other time-consuming operations that don't require immediate feedback.
Conclusion:
We described in detail how to establish a BackgroundService in.NET Core in this article. We learned how to implement the ExecuteAsync method, derive from the BackgroundService base class, and register the service with the host. With this information, making long-running background services in .NET Core should be simple for you. Overall, using a BackgroundService in ASP.NET Core is a convenient and efficient way to implement long-running, background tasks that are an essential part of many web applications.
Hope you enjoyed reading this article and found it useful. Please share your thoughts and recommendations in the comment section below.
Share This Post
Support Me